指定cin值(c ++) [英] specifying a cin value (c++)

查看:187
本文介绍了指定cin值(c ++)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有:

int lol;
cout << "enter a number(int): ";
cin >> lol
cout << lol;

如果我键入5,那么它将cout 5.如果我键入fd它支持一些数字。
如何指定值,就像我只想要一个int?

If I type 5 then it'll cout 5. If I type fd it couts some numbers. How can I specify the value, like say I only want it an int?

推荐答案

code> fd 它会输出一些数字,因为这些数字是什么 lol 恰巧在它们被分配到之前。 cin>> lol 不会写入 lol ,因为它没有可接受的输入,所以它只是离开它,它的值是什么在呼叫之前。然后你输出它(它是UB)。

If you type in fd it will output some numbers because those numbers are what lol happens to have in them before it gets assigned to. The cin >> lol doesn't write to lol because it has no acceptable input to put in it, so it just leaves it alone and the value is whatever it was before the call. Then you output it (which is UB).

如果你想确保用户输入了可接受的,你可以包装

If you want to make sure that the user entered something acceptable, you can wrap the >> in an if:

if (!(cin >> lol)) {
    cout << "You entered some stupid input" << endl;
}

也可以分配 code>读取之前,如果读取失败,它仍然有一些可接受的值(不是UB使用):

Also you might want to assign to lol before reading it in so that if the read fails, it still has some acceptable value (and is not UB to use):

int lol = -1; // -1 for example

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

If, for example, you want to loop until the user gives you some valid input, you can do

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

这篇关于指定cin值(c ++)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆