指定cin值(c ++)

0 c++ int cout

说我有:

int lol;
cout << "enter a number(int): ";
cin >> lol
cout << lol;
Run Code Online (Sandbox Code Playgroud)

如果我输入5然后它会输出5.如果我键入fd它会输出一些数字.我怎样才能指定值,比如说我只想要一个int?

Set*_*gie 7

如果你键入fd它会输出一些数字,因为这些数字是lol在它们被分配之前发生的数字.将cin >> lol不写入lol,因为它没有可接受的输入投入在里面,所以它只是离开它单独和值就是它的调用之前.然后输出它(即UB).

如果您想确保用户输入了可接受的内容,您可以将其包装>>if:

if (!(cin >> lol)) {
    cout << "You entered some stupid input" << endl;
}
Run Code Online (Sandbox Code Playgroud)

此外,您可能希望lol在读取之前分配给它,以便在读取失败时,它仍然具有一些可接受的值(并且不使用UB):

int lol = -1; // -1 for example
Run Code Online (Sandbox Code Playgroud)

例如,如果你想循环直到用户给你一些有效的输入,你就可以这样做

int lol = 0;

cout << "enter a number(int): ";

while (!(cin >> lol)) {
    cout << "You entered invalid input." << endl << "enter a number(int): ";
    cin.clear();
    cin.ignore(numeric_limits<streamsize>::max(), '\n');
}

// the above will loop until the user entered an integer
// and when this point is reached, lol will be the input number
Run Code Online (Sandbox Code Playgroud)