我需要制作一个读取用户体重/高度的程序。
用户需要能够输入一个数字,然后是一个度量单位。单位可以是英尺/英寸、米或厘米。
我已经完成了所有这些工作,但用户还应该能够编写诸如 5' 之类的内容,并且英寸是可选的。
这是我遇到的问题:
我有两个用于用户输入的变量,一个是 double 变量(高度),另一个是字符串变量(unitHeight)。这适用于 m 和 cm,但对于英尺/英寸,我需要再添加两个,因为用户需要输入两个字符串和两个数字(为了简单起见,我将其保留为 double )。
所以我使用了 if 语句:
if (unitHeight == "'"){
cin >> height2;
cin >> unitHeight2;
}
问题是我需要这样做,以便当用户输入 x'(x 是任何数字)时,程序不会要求任何进一步的输入。
最佳答案
要做什么取决于高度之后可能出现的其他输入(如果有的话),以及您希望如何处理错误,但首先要开始:
int height2 = 0;
if (unitHeight == "'" && cin >> height2)
{
if (!(cin >> unitHeight2))
{
std::cerr << "hey, " << height2 << " what? give me units baby!\n";
exit(EXIT_FAILURE);
}
// if we get here, then we have height2 and unitHeight2 to work with...
...
}
else if (cin.eof())
{
// might have hit EOF without inches, that could be legal - depends on your program
...
}
else
{
// saw some non-numeric input when expecting height2 - is that ok?
...
}
自您发帖以来,您添加了一条评论,表示您特别希望在一行中输入此内容,然后用户可以按回车键。为了处理这个问题,用 std::string line; if (getline(std::cin, line)) { std::istringstream iss(line); >>above code goes here<< } else { ...couldn't read a line of input...}
包围上面的代码.
分别来说,你说:
the user needs to be able to input a number and then a unit of measurement right after. this can be in feet/inches, meters, or cm. ive gotten all that to work
...我希望如此,但请注意,支持例如5'11"和 180cm,如 cin >> height1 >> unitHeight1
,当 unitHeight1
是 std::string
时,将显示为“'11”。如果你将 unitHeight1
设置为 char
,那么它将倾向于只读取“c”来自“cm”,所以这两种符号都不适用于这两种表示法。您最好读取一个字符,然后使用它来决定是否读取另一个....
关于c++ - 如何使函数不要求基于初始输入的额外输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21178055/