c++ - 如果 cpp 中的数据类型条目不正确,如何允许多个输入?

标签 c++

我有一个程序可以生成随机数并要求用户不断猜测直到他/她猜对为止。我希望它继续接受新值,即使我通过处理错误情况错误地输入了任何其他数据类型。

我的问题是,当我尝试运行下面的程序时,只要我输入一个字符并按下回车键,它就会进入无限循环。我尝试使用 cin.ignore() 和 cin.clear() 但这只会让程序在第一次输入后停止。

任何人都可以帮助我了解发生了什么以及如何实现所需的输出吗?提前致谢。

#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;

int main()
{
  int secret_num, guess;
  srand(time(NULL));
  secret_num=rand() %  101 + 0;
  cout<<"Enter your guess between 0 and 100: ";

do
 {
  if(!(cin>>guess))
  {
    cout<<" The entered value is not an integer"<<endl;
  }
  else if( isnumber(guess))
    {
      if(guess>secret_num)
        cout<<"Too high";
      else if(guess<secret_num)
        cout<<"too low";
    cout<<endl;
    }
 }
  while(secret_num!=guess);


  if((guess==secret_num)| (isnumber(guess)))
  {
    cout<<"yes the correct number is "<<secret_num<<endl;
  }

  return 0;
}

编辑:这是在我的代码中使用 cin.clear() 和 cin.ignore(1000,'\n') 输出的屏幕截图,当我在输入字符两次后输入一个数字时。 enter image description here

最佳答案

    if (!(cin >> guess))
    {           
        cout << " The entered value is not an integer" << endl;
        cin.clear(); // clear must go before ignore

        // Otherwise ignore will fail (because the stream is still in a bad state)
        cin.ignore(std::numeric_limits<int>::max(), '\n'); 
    }

默认情况下,cin.ignore 将忽略单个字符。如果他们键入超过 1 个字符,这将是不够的,这就是为什么我对其进行了一些修改。

if ((guess == secret_num) | (isnumber(guess)))

| 是位运算符 [OR]

|| 是逻辑运算符 [OR]

但我认为你真正想要的是 && (AND)

if ((guess == secret_num) && (isnumber(guess)))

关于c++ - 如果 cpp 中的数据类型条目不正确,如何允许多个输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35402763/

相关文章:

c++ - "int duplicate = num"是如何用于此代码段的?

c++ - 懒惰、重载的 C++ && 运算符?

c++ - 如何使用 Rand() 随机选择一个变量

c++ - 遍历一组指针

c++ - 在编译时检查函数是否具有 C 链接 [无法解决]

c++ - 为什么这个 "optimization"会减慢我的程序?

c++ - 使用 make_tuple 方法获取元组和 func 并返回映射元组的最简单方法

Javascript C++ 绑定(bind)?

C++对象返回

c++ - 如何将正则表达式 vector 与一个字符串匹配?