带空格的输入输入所有循环

Input with spaces inputs all loops

本文关键字:输入 循环 空格      更新时间:2023-10-16

我让我的程序在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
}