指定 cin 值 (c++)

发布于 2025-01-02 06:34:16 字数 191 浏览 3 评论 0原文

假设我有:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

眼眸 2025-01-09 06:34:16

如果您输入fd,它将输出一些数字,因为这些数字是lol在被分配之前恰好包含在其中的数字。 cin>> lol 不会写入 lol ,因为它没有可接受的输入可放入其中,因此它只是保留它,并且该值是调用之前的值。然后输出它(即UB)。

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

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

您也可能希望分配给 lol 在读入之前,这样如果读取失败,它仍然具有一些可接受的值(并且不可以使用 UB):

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

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

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

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;
}

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文