-3

我写了一个关于猜测密码的代码,但是当输入字母字符而不是整数时,我遇到了问题。它停止程序。我该如何抗拒这个问题。

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;
4

2 回答 2

0

您不必这样做,但如果您仍然想解决问题,您可以流式传输线路并仅获取线路编号。

杰西·古德在这里回答

我会使用std::getlineandstd::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;
}
于 2016-05-17T10:44:44.113 回答
0

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

  1. 初始化为0 ,提取后a如果为0:a
  2. clear cin
  3. ignore cin(注意指定要忽略到换行符:Cannot cin.ignore until EOF?

您的最终代码应如下所示:

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

于 2016-05-17T11:30:40.323 回答