[英]Entering specific character into while loop
I am writing a code for class that asks the user to input a size that is an odd number equal to or greater than 7
. 我正在为班级编写代码,要求用户输入大小等于或大于
7
的奇数。 I have been able to make that part of my code work successfully. 我已经能够使我的代码部分成功工作。 However, the next part consists of asking the user to enter a specific letter, in this case
'c'
. 但是,下一部分包括要求用户输入特定字母,在这种情况下为
'c'
。 If they do not enter 'c'
then the loop should ask them to input another character. 如果他们没有输入
'c'
则循环应要求他们输入另一个字符。 Whenever I run this code, it is creating an infinite loop whether I enter 'c'
or another letter. 每当我运行此代码时,无论我输入
'c'
还是另一个字母,它都会创建一个无限循环。 I think my expression in my second while
loop is incorrect, but I haven't been able to find a lot of information regarding this that could help me. 我认为我的第二个
while
循环中的表达式不正确,但是我无法找到很多有关此方面的信息可以帮助我。
#include <iostream>
using namespace std;
int main() {
int s, l;
cout << "Welcome to the letter printer." << endl;
cout << "Enter the size: " << endl;
cin >> s;
while (s < 7 || s%2==0 || s<0)
{
cout << "Invalid size. Enter the size again: " << endl;
cin >> s;
}
cout << "Enter the letter: " << endl;
cin >> l;
while (l != 'c')
{
cout << "Invalid letter. Enter the letter again: " << endl;
cin >> l;
}
return 0;
}
because you are getting char for int variable 因为您正在为int变量获取char
wrong: 错误:
int s, l;
right one: 正确对象,真爱:
int s;
char l;
what is why it goes on infinite loop in second while 为什么它会在一秒钟内无限循环
explanation for infinite loop 无限循环的解释
This is how basic_istream works.
这就是basic_istream的工作方式。 In your case when cin >> l gets wrong input - failbit is set and cin is not cleared.
在cin >> l输入错误的情况下-设置了故障位并且未清除cin。 So next time it will be the same wrong input.
所以下一次它将是相同的错误输入。 To handle this correctly you can add check for correct input and clear&ignore cin in case of wrong input.
要正确处理此问题,您可以添加检查输入是否正确,并在输入错误的情况下清除并忽略cin。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.