while loop to infinity when the input of a cin is a #39;dot#39;(当 cin 的输入是一个“点时,while 循环到无穷大)
问题描述
我在使用 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 char
s (well, their ASCII codes, actually), you will be able to check it without troubles.
这篇关于当 cin 的输入是一个“点"时,while 循环到无穷大的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:当 cin 的输入是一个“点"时,while 循环到无穷大


基础教程推荐
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 从 std::cin 读取密码 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01