我有一个程序要求用户输入 [0,2] 范围内的整数。我使用以下链接作为指南。
使用 cin - C++ 进行良好的输入验证循环
但是,当用户按 Enter 键而不输入数据时,光标只会转到命令提示符中的下一行,而我更希望它提示用户输入有效数字。在这种情况下提示用户是否有意义,或者是否有理由不首先将验证实现为单行输入?对于字符串,我会使用 getline 来解决这个问题,在这种情况下我应该以某种方式使用它吗?这是我的代码,基于上面的链接:
#include <iostream>
int main()
{
int answeredNumber;
while(1)
{
std::cout << "Enter your answer: ";
if(std::cin >> answeredNumber && answeredNumber >= 0 && answeredNumber <= 2)
{
break;
}
else
{
std::cout << "Please enter a valid answer: " ;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
system("pause");
}
那是因为得到一个整数cin
将跳过前导空格,包括换行符。没有简单的方法可以解决这个问题。
如果您想要基于行的输入,您可以将输入值作为string然后解释一下:
#include <iostream>
#include <sstream>
#include <string>
int main (void) {
std::string inputLine;
int answer;
std::cout << "Enter your answer: ";
while(1) {
getline (std::cin, inputLine);
std::stringstream ss (inputLine);
if ((ss >> answer))
if ((answer >= 0) && (answer <= 2))
break;
std::cout << "No, please enter a VALID answer: " ;
}
std::cout << "You entered " << answer << '\n';
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)