简体   繁体   English

如何在C ++中仅cin整数而不破坏其余代码?

[英]How to cin only integers in C++ without disrupting remaining code?

I would like my code to only input integers. 我希望我的代码仅输入整数。 The code below does it's job correctly and asks the user for input if an integer was not used. 下面的代码正确地完成了工作,并询问用户是否未使用整数。 However, after adding the code: 但是,添加代码后:

while ( ! ( cin >> x ))
    {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cout << "Enter a number: ";
    }

into the code below, it only works when I enter a non-integer first. 在下面的代码中,它只有在我首先输入非整数时才有效。 Otherwise if I enter an int first, the program doesn't move on to the next statement and doesn't do anything. 否则,如果我先输入一个int,该程序将不会继续执行下一条语句,并且不会执行任何操作。 My reasoning was that if x = int then the while loop would not be started. 我的理由是,如果x = int,则while循环将不会启动。 So why is it that adding the code messes up the remaining code. 那么,为什么添加代码会弄乱其余的代码。

#include <iostream>
#include <limits>
using namespace std;

main ()

{

cout << "Enter a number: ";

int x, y;
cin >> x;

while ( ! ( cin >> x ))
    {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cout << "Enter a number: ";
    }

cout << "Enter a number: ";
cin >> y;

The problem is that you are reading from cin 1 time too many: 问题是您从cin读取的次数过多:

int x, y;
cin >> x; // <-- reads an int, without validation! 

while ( ! ( cin >> x )) { // <-- reads ANOTHER int! 

You need to get rid of the first read before entering the while loop. 在进入while循环之前,您需要摆脱第一次读取的内容。 Let the loop alone do the reading: 让循环独自阅读:

#include <iostream>
#include <limits>

using namespace std;

main () {
    int x, y;
    // <-- NO READ HERE!

    cout << "Enter a number: ";
    while (!(cin >> x)) {
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        cout << "Enter a number: ";
    }

    // same as above, for y ...     
}

Alternatively, use a do..while loop instead: 或者,使用do..while循环代替:

#include <iostream>
#include <limits>

using namespace std;

main () {
    int x, y;
    // <-- NO READ HERE!

    do {
        cout << "Enter a number: ";
        if (cin >> x) break;
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }
    while (true);

    // same as above, for y ...     
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM