【问题标题】:How to restart loop if an alphabet is given as input by user in C++如果用户在 C++ 中输入字母表,如何重新启动循环
【发布时间】:2016-05-17 10:12:26
【问题描述】:

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

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;

【问题讨论】:

  • 代码无法编译。向我们展示实际代码。 (如果第一个在哪里?)
  • 如果输入流在无效输入后给出,你必须使用cin.clear()重置失败状态。
  • 查看continue关键字
  • @πάνταῥεῖ clear 很好,但这里也需要ignore

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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    在你的情况下,因为 0 超出了允许范围,这真的很简单:

    1. a初始化为0,如果a解压后为0:
    2. clearcin
    3. ignorecin(注意指定要忽略到换行符:Cannot cin.ignore till 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-14
      • 2014-11-30
      • 1970-01-01
      • 1970-01-01
      • 2021-12-03
      • 1970-01-01
      相关资源
      最近更新 更多