gpt4 book ai didi

c++ - 如何在不中断剩余代码的情况下仅 cin C++ 中的整数?

转载 作者:行者123 更新时间:2023-11-28 04:45:36 25 4
gpt4 key购买 nike

我希望我的代码只输入整数。下面的代码正确地完成了它的工作,并在没有使用整数的情况下要求用户输入。但是,添加代码后:

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

进入下面的代码,只有当我首先输入一个非整数时它才有效。否则,如果我先输入一个 int,程序不会继续执行下一条语句,也不会执行任何操作。我的推理是,如果 x = int 那么 while 循环将不会启动。那么为什么添加代码会弄乱剩余的代码。

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

最佳答案

问题是您从 cin 中读取的次数太多了 1 次:

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

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

在进入 while 循环之前,您需要去掉第一次读取。让循环单独进行读取:

#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 ...
}

或者,使用 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 ...
}

关于c++ - 如何在不中断剩余代码的情况下仅 cin C++ 中的整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49345728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com