指定 cin 值 (c++)
假设我有:
int lol;
cout << "enter a number(int): ";
cin >> lol
cout << lol;
如果我输入 5 那么它会计算出 5。如果我输入 fd 它会计算出一些数字。 我如何指定该值,比如我只想要一个 int ?
say I have:
int lol;
cout << "enter a number(int): ";
cin >> lol
cout << lol;
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您输入
fd
,它将输出一些数字,因为这些数字是lol
在被分配之前恰好包含在其中的数字。cin>> lol
不会写入lol
,因为它没有可接受的输入可放入其中,因此它只是保留它,并且该值是调用之前的值。然后输出它(即UB)。如果您想确保用户输入了可接受的内容,您可以将
>>
包装在if
中:您也可能希望分配给
lol
在读入之前,这样如果读取失败,它仍然具有一些可接受的值(并且不可以使用 UB):例如,如果您想循环直到用户给您提供一些有效的输入,您可以做
If you type in
fd
it will output some numbers because those numbers are whatlol
happens to have in them before it gets assigned to. Thecin >> lol
doesn't write tolol
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 anif
: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):If, for example, you want to loop until the user gives you some valid input, you can do