C++输入为什么当我输入一个字母时会返回0
C++ Input Why is a 0 returned when I input a letter?
我目前设置了一个函数,要求用户输入一个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;
}
相关文章:
- 在 Arduino 上使用 sscanf 会导致与 const char * 不匹配,并且返回值始终相同,尽管输入值不同
- 从 cin 读取不会返回整个输入字符串
- 程序中的布尔函数返回输入的范围无论如何都是无效的
- 返回C++输入
- C++模板编程设计问题 - 根据输入文件返回不同的类型
- cpp 返回具有相同输入的不同输出
- 从子菜单返回后,正确的输入至少进入验证循环一次
- C++ CIN 值返回 0 而不是输入值
- 输出返回编号。等于输入字符串的单词的字符串数
- 函数重载并根据相同的输入返回不同的数据类型
- 如何根据输入C++更改返回类型?
- 函数返回包含输入容器的特定元素的容器
- C++输入为什么当我输入一个字母时会返回0
- 阶乘函数只返回C++中输入的答案
- 查找匹配的输入,并返回匹配的输入和不匹配的输入
- 函数使用任何输入返回 0
- C++根据输入返回一个字符串或一个int
- 字符串.输入返回true始终(C )
- 函数根据输入返回不同的类型
- LIBC的mktime函数对于相同的输入返回不同的值