2016-12-04 15 views
0

私のコードで例外処理を使用して無限ループを排除しようとしていますが、そのコードが動作していない人がこのスニペットを見て、間違ってる?彼らが最初にスローされた場合C++どのようにwhileループで例外処理をして入力エラーを拾うのですか

void Addition(float num) 
 
\t { 
 
\t \t 
 
\t \t cout<<"Please enter number you wish to add:"<<endl; 
 
\t \t cin>>num; 
 
\t \t 
 
\t \t while(num!=-9999) 
 
\t \t { 
 
\t \t \t Sum+=num; 
 
\t \t \t cout<<"Sum is:"<<Sum<<endl; 
 
\t \t \t cout<<"Please enter number or enter -9999 to exit"<<endl; 
 
\t \t \t try{ 
 
\t \t \t \t cin>>num; 
 
\t \t \t } 
 
\t \t \t catch(...) 
 
\t \t \t {cout<<"ERROR"<<endl; 
 
\t \t \t } 
 
\t \t 
 
\t \t \t 
 
\t \t } 
 
\t \t 
 
\t \t 
 
\t }

+1

最後にcatchブロックの 'num = -9999;'を追加してください。または、終了するかどうかを示すメッセージを出力します。-9999 – doug

+0

例外はwhileループ内で捕捉され、実行は単に続行されます。例外が 'while'ループを終了させたい場合は、try/catchをループ外に置かなければなりません。 'while'ループ全体は' try'ブロックの中になければなりません。 –

+0

このような*マジックナンバー*を使わないでください。もし誰かが '-9999'を加算する必要があればどうしますか?これは 'eof()'シグナルのためのものです。 – tadman

答えて

1

例外は唯一のキャッチされています。コードのどの部分も、throwキーワードを使用して例外をスローしません。しかし、あなたはそれがあなたの意図

かどうbreak文を使ってループを終了する必要がありますのでごcatchブロックが同様のループでなければならないことを行う場合でも、あなたは、次の

void Addition(float num) 
    { 
     int Sum=0; 
     cout<<"Please enter number you wish to add:"<<endl; 
     cout<<"Please enter number or enter -9999 to exit"<<endl; 

     while(true) // whcih actually makes it infinite 
     { 
      try{ 
       cin>>num; 
       if(num == -9999) 
        throw -9999; // you can throw any value in this case 
       Sum+=num; 
      } 
      catch(...) 
      { 
      cout <<" ABORTING.."<<endl; 
      break; 
      } 
     } 

     cout << "Sum is:" << Sum << endl; 
    } 

上記のコードは行うことができます

void Addition(float num) 
     { 
      int Sum=0; 
      cout<<"Please enter number you wish to add:"<<endl; 
      cout<<"Please enter number or enter -9999 to exit"<<endl; 

      while(true) // whcih actually makes it infinite 
      { 

        cin>>num; 
        if(num == -9999) 
        { 
         cout << "ABORTING.." << endl; 
         break; 
        } 

        Sum+=num; 
      } 

      cout << "Sum is:" << Sum << endl; 
     } 
+1

さらに良い: 'while(std :: cin >> num && num!= -9999)'。 –

関連する問題