C++ 使用空格输入所有循环

C++ 使用空格输入所有循环,c++,if-statement,while-loop,cin,C++,If Statement,While Loop,Cin,我的程序要求在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: ";

我的程序要求在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');
        }
    }
int input1=0
而(!(cin>>输入1)| |输入1<0)
{
如果(!cin)
{
cout>input2)| | input2<0)
{
如果(!cin)
{
cout>input3)| | input3<0)
{
如果(!cin)
{
cout您可以使用一次读取整行(包括空格),然后使用以下命令检查字符串中是否存在空白:


为什么不
std::string in=std::cin.getline()
?我明白这一点。我认为您还应该添加
stringstream
,并在else中将输入转换为int。@SHR,我找不到没有参数的
std::basic\u istream::getline
的文档。您得到了我的投票……您需要给它最大缓冲区和字符串大小。@user3398034,然后您可以使用将字符串转换为int(如果不包含空格)。
std::string in;
std::getline(std::cin, in);
if (in.find(' ') != std::string::npos) {
    // whitespace found / error
} else {
    // no whitespace found
}