2017-11-22 47 views
-1

基本的には私の学校のクラブのための基本的なプログラムを作る必要があります。ユーザーが数字ではないものを入力したときに、エラーメッセージが表示され、番号をもう一度尋ねるために折り返している場所に移動しようとしています。これは正確なことではありませんが、私が例として実際に素早く一緒に投げたものです。番号の入力のみに制限するにはどうすればよいですか?

#include <iostream> 
#include <string> 
#include <iomanip> 
#include <cstdlib> 
#include <ctime> 

using namespace std; 

int main() { 
int a; 
int b; 

do{ 
cout << "Welcome to the equalizer. Please enter a number." << endl; 
cin >> a; 

cout << endl << "Ok, now I need another number." << endl; 
cin >> b; //if a number is not entered, I need an error message and a loop back to the request for the number. 
if(a>b){ 
cout << a << " is greater than " << b << endl; 

     } 
if(b>a){ 
cout << b << " is greater than " << a << endl; 

     } 
if(b=a){ 
cout << a << " is equal to " << b << endl; 

     } 
cout << "restart? Enter Y if yes, or enter anything else to close." << endl; 
cin >> c; 

}while(c=="y" || c=="Y"); 

return 0; 
+0

'' cin >> a'演算の結果をテストするだけです。 'if(!(cin >> a)){/ *無効な入力、ストリーム状態のクリーンアップ、* /}'のように ' – user0042

+0

ユニバーサルチェック入力アルゴリズム:テキスト行を読み込みます。それに悪い文字がないかチェックしてください。それが大丈夫なら使用し、そうでなければエラーメッセージを表示する。完了するまで繰り返す。 –

答えて

0

私が正しいとすれば、「isdigit( 'char')」のようなものを使うことができます。 "ctype.h"を含めることを忘れないでください。あなたのコードで それはのようなものになります。番号は「1232321」のような文字列でもあれば、あなたはそれがない場合は、各文字と終了をチェックし、その文字列を反復処理する必要があるかもしれません

if (!isdigit(c)) 
    continue; 

...

bool error = false;  
for (int i = 0; i < c.length(); i ++) 
    { 
     if (!isdigit(c[i])) 
     { 
      error = true; 
      break; 
     } 
    } 

希望すると、これが役に立ちます。

P.S.もちろん、あなたの例の "a"と "b"は文字列かchar型でなければなりません。

関連する問題