如果用户在C ++中输入字母表,如何重新启动循环

时间:2016-05-17 10:12:27

标签: c++ loops user-input invalid-characters defensive-programming

我编写了一个关于猜测密码的代码,但是当字母字符作为输入而不是整数给出时,我遇到了问题。它停止了该计划。我怎么能抵抗这个问题。

srand(time(0));
int a,secret;
secret=rand() % 10 +3;
do{
        cout<<"Guess the secret num between 1-10 + 3 : ";
cin>>a;
else if(a>secret)
{
    cout<<"Secret num is smaller!!"<<endl;
}
else if(a<secret) {
    cout<<"Secret num is greater !!"<<endl;
}

}
while(a!=secret)
cout<<"   "<<endl;
cout<<""<<endl;
    cout<<"Congratulations!!!! This is the secret num...."<<secret<<endl;

2 个答案:

答案 0 :(得分:0)

您不必这样做,但如果您仍想解决问题,则可以对该行进行流式处理并仅获取该行号。

Answered by Jesse Good here

  

我会使用std::getlinestd::string来阅读整行   然后只有在你可以转换整个循环时才会突破循环   排成双线。

#include <string>
#include <sstream>

int main()
{
  std::string line;
  double d;
  while (std::getline(std::cin, line))
  {
      std::stringstream ss(line);
      if (ss >> d)
      {
          if (ss.eof())
          {   // Success
              break;
          }
      }
      std::cout << "Error!" << std::endl;
  }
  std::cout << "Finally: " << d << std::endl;
}

答案 1 :(得分:0)

在您的情况下,因为0超出允许范围,所以这很简单:

  1. a初始化为0,并在解压后将a设为0:
  2. clear cin
  3. ignore cin(请注意指定您要忽略换行符:Cannot cin.ignore till EOF?
  4. 您的最终代码应如下所示:

    cout << "Guess the secret num between 1-10 + 3 : ";
    cin >> a;
    
    while (a != secret) {
        if (a == 0) {
            cin.clear();
            cin.ignore(std::numeric_limits<streamsize>::max(), '\n');
            cout << "Please enter a valid number between 1-10 + 3 : ";
        }
        else if (a < secret) {
            cout << "Secret num is smaller!!\nGuess the secret num between 1-10 + 3 : ";
        }
        else if (a < secret) {
            cout << "Secret num is greater !!\nGuess the secret num between 1-10 + 3 : ";
        }
        a = 0;
    
        cin >> a;
    }
    

    Live Example