为什么我的质量计算器不能在空格上正常工作
Why does my mass calculator not work properly with 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
没有空间的重量单位效果很好。问题是长tn(长吨)和sh tn(短吨)单位不起作用,我假设这是因为字符串之间的空间。谁能帮忙。提前谢谢。
std::istream
在此处使用的operator>>(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
末尾手动剥离它们。
istream::operator>>
对空格字符进行标记。当您输入 sh tn
时,只有sh
会保存在unitType
中,tn
将保留在流中。
当您在流中获得sh
或long
时,请检查另一个令牌并查看它是否tn
。一个健壮的解决方案可能是一个具有自由函数std::istream& operator>>(std::istream, Unit&)
的Unit
类,用于执行流提取。
相关文章:
- QSqlquery prepare()和bindvalue()不工作
- 导入库可以跨dll版本工作吗
- 以螺旋方式打印矩阵的程序.(工作不好)
- 对象指针在c++中是如何工作的
- 为什么在Windows上的VS 2019和Clang 9中"size_t"在没有标题的情况下工作
- VSOMEIP-2个设备之间的通信(TCP/UDP)不工作
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- C++为线程工作动态地分割例程
- 为什么我的 std::ref 无法按预期工作?
- 布尔比较运算符是如何在C++中工作的
- SampleConsensusPrerejective(ext.RANSAC)是如何真正工作的
- 不确定要在我的main中放入什么才能使我的代码正常工作
- 为什么std::condition_variable notify_all的工作速度比notify_one快(对于随机请
- <<操作员在下面的行中工作
- 有人能解释一下为什么下界是这样工作的吗C++的
- ExtractIconEx:可以工作,但偶尔会崩溃
- C++中的memset函数工作不正常
- 当我在第一个循环中使用"auto"时,它工作正常,但是使用"int"它会给出错误,为什么?
- 为什么STD ::计数将常数传递给Lambda,而不是在弦上工作时而不是字符
- C++程序已停止工作-求解常微分方程