问题描述
我在使用 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
2.troll
3.zombie"<<endl;
cin >> *race;
while(*race<1||*race>3)
{
system("cls");
cout << "Wrong choice"<<endl<< "What is your race" <<endl<<"1.Human
2.troll
3.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 chars (well, their ASCII codes, actually), you will be able to check it without troubles.
这篇关于当 cin 的输入是一个“点"时,while 循环到无穷大的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)