c++ - 为什么我的质量计算器不能正确处理空格?

标签 c++ string spaces

#include <iostream>
#include <string>



using namespace std;

/*
Function Name: weightConv
Purpose: To take the weight and convert the following number to the coressponding weight unit
Return : 0
*/
  double weightConv(double w, string weightUnit)
{

      if (weightUnit == "g" || weightUnit == "G" )
        cout << " Mass = " <<  w * 0.035274 << "oz";
    else if (weightUnit == "oz"||weightUnit == "OZ"||weightUnit == "oZ" ||weightUnit == "Oz")
        cout << " Mass = " <<  w / 28.3495 << "g";
    else if (weightUnit == "kg"||weightUnit == "KG"||weightUnit == "Kg" ||weightUnit == "kG")
        cout << " Mass = " <<  w * 2.20462 << "lb";
    else if (weightUnit == "lb" ||weightUnit == "LB" ||weightUnit== "Lb" ||weightUnit == "lB")
        cout << " Mass = " <<  w * 0.453592 << "kg";
    else if (weightUnit == "Long tn" ||weightUnit == "LONG TN"|| weightUnit == "long tn" || weightUnit == "long ton")
        cout << " Mass = " <<  w * 1.12 << "sh tn";
    else if (weightUnit == "sh tn" || weightUnit == "SH TN")
        cout << " Mass = " << w / 0.892857 << " Long tons";
    else if (weightUnit == "s" || weightUnit == "S")
        cout << " Mass = " << w * 6.35029 << "stones";
    else
        cout << "Is an unknown unit and cannot be converted";

    return 0;   
}// end of weightCov function


int main()
{
    for (;;)
    {

        double mass;
        string unitType;
        cout << "Enter a mass and its unit type indicator(g,kg,lb,oz,long tn,or sh tn)" << endl;
        cin >> mass >> unitType;

            // Output Results
            cout << weightConv(mass, unitType) << endl;

    }// end of for loop
}// end of main 

没有空格的重量单位效果很好。问题是 Long tn(Long ton) 和 sh tn (short ton) 单位不起作用,我假设这是因为字符串之间的空间。谁能帮忙。提前致谢。

最佳答案

您在此处使用的

std::istreamoperator>>(std::string &):

cin >> mass >> unitType;

读取以空格分隔的标记。这意味着当您在输入流中输入 "12 long tn" 时,mass 将为 12.0,并且 unitType 将是 "long"

您的问题的解决方案可能涉及std::getline,如

std::cin >> mass;
std::getline(std::cin, unitType);

这将一直读到下一个换行符。但是,这不会像 operator>> 那样去除前导空格,因此您将得到 "long tn" 而不是 "long tn"。您需要像这样显式地忽略这些空格:

std::cin >> std::ws;

这最终留给你

std::cin >> mass >> std::ws;      // read mass, ignore whitespaces
std::getline(std::cin, unitType); // the rest of the line is the unit

请注意,这不会删除尾随 空格,因此如果您的用户键入"12 long tn ",它将无法识别该单位。如果这是一个问题,您必须从 unitType 的末尾手动删除它们。

关于c++ - 为什么我的质量计算器不能正确处理空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28239215/

相关文章:

c++ - 为什么有一个本地仿函数不好?

Python 从 DataFrame 字符串字段中去除所有空格

java - 如何将字符串变量值分配给二维数组

mysql - 在 mysql 中选择名称中包含空格的数据库

html - 带背景图像的 div 周围的空间

C++ lambda 捕获约束

c++ - 如何为 boost::tokenizer 实现 tokenizer.rbegin() 和 rend()?

c++ - 当指针作为指向另一个函数内部指针的指针传递时会发生什么?

c - 为什么在 C 中我的字符串后打印数字 '7'?

c - Text::JaroWinkler::strcmp95 的第三个参数是什么?