带空格的输入输入所有循环
Input with spaces inputs all loops
我让我的程序在3个不同的while循环中请求3个输入。为什么我输入
4 2 5用空格填充所有输入input1,input2,input3?如果发生这种情况,有没有办法让它给出一个错误?
int input1 = 0
while (!(cin >> input1) || input1 < 0)
{
if (!cin)
{
cout << "Please enter a positive value: ";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), 'n');
}
}
int input2 = 0
while (!(cin >> input2) || input2 < 0)
{
if (!cin)
{
cout << "Please enter a positive value: ";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), 'n');
}
}
int input3 = 0
while (!(cin >> input3) || input3 < 0)
{
if (!cin)
{
cout << "Please enter a positive value: ";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), 'n');
}
}
您可以使用std::getline
一次性读取整行(包括空格),然后您可以使用std::string::find
:
std::string in;
std::getline(std::cin, in);
if (in.find(' ') != std::string::npos) {
// whitespace found / error
} else {
// no whitespace found
}
相关文章:
- 正在尝试了解输入验证循环
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 通过for循环使用用户输入填充列表
- 我试图制作一个程序,要求用户输入问题和答案,但程序循环不正确
- 使用输入打破 OpenMP 中的循环
- 如何读取单个字符并在输入两个字符序列时输出? 使用 while 循环和C++
- 遇到此问题时遇到困难:允许用户输入数组的值并使用 for,而循环也输出输入的最大数字
- 如何使用递归循环我的代码(当用户输入无效输入时,它会再次提示他们)?
- 偶尔多次请求用户输入循环
- 如何用字符终止整数输入循环?
- CIN 到矢量输入循环无限期.为什么
- 结构卡在输入循环中的函数
- C++Visual Studio 2017中,无法输入循环中的变量
- 用于读取文件的输入循环
- C++ 文件输入循环的困难
- 输入循环 while 函数
- 巧克力游戏:输入循环,不插入循环或打印游戏统计数据
- 使用自动输入循环错误"auto must have an initializer"
- 通过用户输入循环的更好方法
- Scala/ c++:尾部递归函数代替输入循环