当cin的输入是“点"时,while循环到无穷大 [英] while loop to infinity when the input of a cin is a 'dot'
问题描述
使用cin方法获取变量时遇到麻烦.当输入是数字时,没有问题,但是当它是特殊字符(例如点[.])时, whileloop循环成无穷大. 我在做什么错了?
I am having trouble using the cin method to acquire a variable. When the input is a number there is no problem, but when it is a special character like a dot [.], the whileloop loops into infinity. What am I doing wrong?
cout << "What is your race" <<endl<<"1.Human\n2.troll\n3.zombie"<<endl;
cin >> *race;
while(*race<1||*race>3)
{
system("cls");
cout << "Wrong choice"<<endl<< "What is your race" <<endl<<"1.Human\n2.troll\n3.zombie"<<endl;
cin >> *race;
}
我搜索了答案,我应该刷新缓冲区,但是我不知道该怎么做.我对c ++还是很陌生.谢谢
I searched for the answer and i should have to flush the buffer but i don"t get how to do it. I'm rather new with c++. Thanx
推荐答案
将race
设置为字符,则您可以执行以下操作:
Make race
an char, then you will be able do to:
while (*race < '1' || *race > '3')
这可能是您想要实现的.
which is probably what you want to achieve.
说明:
当您将cin >>
转换为int时,它将给定的ASCII字符串转换为整数值. .
没有整数含义,因此不会将其读入race
且已设置failbit
-进一步>> s禁止操作,直到您将其清除.但是,如果您cin >>
进入char
并将其与其他char
(实际上是它们的ASCII码)进行比较,则可以毫无问题地进行检查.
When you cin >>
into an int, it converts given ASCII string to integer value. .
doesn't have an integer meaning, so it isn't read into race
and failbit
is set - further >>s are no-op, until you clear them. However, if you cin >>
into char
and compare it with other char
s (well, their ASCII codes, actually), you will be able to check it without troubles.
这篇关于当cin的输入是“点"时,while循环到无穷大的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!