当 cin 的输入是一个“点"时,while 循环到无穷大

2021-12-26 00:00:00 loops while-loop c++ cin

我在使用 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.

相关文章