2016-12-15 3 views
-4

ループは、qまたはQが与えられるまで入力を受け取ります。ループは整数を期待していますが、qまたはQはループを分割して認識されません。ループでqまたはQを認識してループを解除するにはどうすればよいですか?C++ループは、与えられるまで整数を受け取ります。Q

int ReadInput;  // Remembers input elements given 
string ReadInputString = to_string(ReadInput); // String version of the ReadInput 

     do 
     { 
      bool NoErrors = true; // Make sure there were no errors while reading input 

      std::cout << "Enter the next element (Enter 'q' to stop): "; // Prompt user for input 
      cin >> ReadInput; 

      if (ReadInputString == quit || ReadInputString == Quit) // Enter Q or q to quit 
      { 
       break; 
      } 

      /* Validation */ 
      if (cin.fail()) 
      { 
       /* Pass by the bad input */ 
       NoErrors = false; // Note there was a problem 
       cin.clear(); // Clear the bad input 
       cin.ignore(); // Ignore the bad input 
       std::cout << "Invalid number" << endl; // Error message 
      } 

      /* Add the input to the list (if there were no problems) */ 
      if (NoErrors) 
      { 
       NumbersList.push_back(ReadInput); // Put the given number onto the end of the list 
      } 

     } while (ReadInput >= 0); 
+0

' quit'を破ると、 Quitは何だった? –

+0

あなたのコードにもっと無意味なものもいくつかあります:: 'cin >> ReadInput;' int '値を読み込みますが、それを '' q' 'や' 'Q" 'と比較したいとします。 –

+0

これは、ユーザーに入力を求めているものとはかなり異なっています。 –

答えて

-1

最後に番号を格納する場所はありません。あなたは整数変数の入力を受けていて、charがそこに格納されることを期待していました。これだけ、そこに文字を取り、それは数字が含まれているかどうかを確認、そうならば、NUMに変換して進み、 `それが文字であれば、それはqまたはQでチェックし、YESの場合

int ReadInput; 

char temp; 

string ReadInputString = to_string(ReadInput); // String version of the ReadInput 

     do 
     { 
      bool NoErrors = true; // Make sure there were no errors while reading input 

      std::cout << "Enter the next element (Enter 'q' to stop): "; // Prompt user for input 

      cin >> temp;      //store input as char 
      if (isdigit(temp))     //check input is number or not 
       ReadInput = temp;    //convert input to num if true 
      else if (temp == 'q' | temp == 'Q') //if not number check for q or Q 
       break;       //break if q 

      if (ReadInputString == quit || ReadInputString == Quit) // Enter Q or q to quit 
      { 
       break; 
      } 

      /* Validation */ 
      if (cin.fail()) 
      { 
       /* Pass by the bad input */ 
       NoErrors = false; // Note there was a problem 
       cin.clear(); // Clear the bad input 
       cin.ignore(); // Ignore the bad input 
       std::cout << "Invalid number" << endl; // Error message 
      } 

      /* Add the input to the list (if there were no problems) */ 
      if (NoErrors) 
      { 
       NumbersList.push_back(ReadInput); // Put the given number onto the end of the list 
      } 

     } while (ReadInput >= 0); 
+0

コードの回答のみを掲示することをお勧めします。第一位の 'std :: string'値の読み込みをより簡単に解決できる方法です! –

+0

変更を完全に理解できるように適切なコメントが追加されます – Anmol

+0

これらはveteror NumbersListに保存されています。 – Blake

関連する問題