C++输入为什么当我输入一个字母时会返回0

C++ Input Why is a 0 returned when I input a letter?

本文关键字:输入 返回 一个 为什么 C++      更新时间:2023-10-16

我目前设置了一个函数,要求用户输入一个int,获取该int,然后检查以确保输入符合特定规范。在这种情况下,预计输入将是一个介于-10和100之间的整数。到目前为止,如果我输入任何一个字母字符串,例如"gfUIWYDUF",函数将返回一个0。为什么会发生这种情况,我该如何解决?

int readUserInput() {
cout << "What is the answer?: " << endl;
int answer;
do {
cin >> answer;
if (!cin || answer < -10 || answer > 100) {
cout << "Invalid Input!" << endl;
cout << "What is the answer?: " << endl;
cin.clear();
cin.ignore();
}
} while(!cin || answer < -10 || answer > 100);
return answer;
}

如果您使用输入值,您会发现cin>>从左到右扫描,直到找到任何非数值。然后,它评估它找到的数字。

例如,放置:

57gh5

返回57

如果只输入数字字符,则得分为0。

如果您改为cin>>字符串,那么您将能够解析/验证该字符串,并将有效数字转换为int

问题是,这种类型输入的验证循环取决于std::cin的错误状态。但是,在循环检查之前,您可以清除该错误状态

解决此问题的最简单方法是将读数从std::cin移动到clear()之后,如下所示:

// Read first
cin >> answer;
do {
if (!cin || answer < -10 || answer > 100) {
cout << "Invalid Input!" << endl;
cout << "What is the answer?: " << endl;
cin.clear();
cin.ignore();
cin >> answer;
}
} while(!cin || answer < -10 || answer > 100);

不过,我想我更喜欢使用常规的while循环,而不是自己:

cin >> answer;
while(!cin || answer < -10 || answer > 100) {
cout << "Invalid Input!" << endl;
cout << "What is the answer?: " << endl;
cin.clear();
cin.ignore();
cin >> answer;
}

这对我来说更干净,但那只是我自己。两个循环都会起作用。

0作为答案的初始值返回

您可以使用cin.fail()来检查输入是否有效。

int readUserInput() {
cout << "What is the answer?: " << endl;
int answer;
do {
cin >> answer;
if (cin.fail() || !cin || answer < -10 || answer > 100) {
cout << "Invalid Input!" << endl;
cout << "What is the answer?: " << endl;
cin.clear();
cin.ignore();
}
} while(cin.fail() || !cin || answer < -10 || answer > 100);
return answer;
}