-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::getlineandを使用しstd::stringて行全体を読み取り、行全体を double に変換できる場合にのみループから抜け出します。

#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 に答える