2017-10-04 13 views
0

この質問のタイトルには挑戦しましたが、私がここで詳しく述べるように私を許してくれることを願っています。 私が抱えている問題は、整数以外のものを入力した場合、私のCプログラムは「学生の等級を入力してください:F」というコンソールにあふれてしまいます。私はC言語を初めて使っているので、入力が有効な型かどうかを調べる方法を理解していません。私のCプログラムが同じ応答でコンソールを氾濫させないようにするにはどうすればいいですか

int main() { 
    int grade; //number 0-10 associated with the letter grade 
    while (1) { 
    printf("Enter the student's grade: "); 
    scanf("%i", &grade); 
    switch (grade) { 
     case 10: printf("A \n"); break; 
     case 9: printf("A \n"); break; 
     case 8: printf("B \n"); break; 
     case 7: printf("C \n"); break; 
     case 6: printf("D \n"); break; 
     case 5: printf("F \n"); break; 
     case 4: printf("F \n"); break; 
     case 3: printf("F \n"); break; 
     case 2: printf("F \n"); break; 
     case 1: printf("F \n"); break; 
     case 0: printf("F \n"); break; 
     default: printf("Please enter a valid test score \n"); break; 
    } 
    } 
    return 0; 
} 

ありがとうございます!

+1

しばらくは、(1)これは再びscanf関数で無限ループ –

+0

です:( –

+0

あなたが他のグレードを置くためにそのscanf関数は待ちません意味ですか? –

答えて

0

scanf関数の戻り値をチェックしてください。 1は整数が正常にスキャンされたことを意味します。 0は入力が整数でないことを意味します。入力ストリームを消去して、もう一度やり直してください。

#include <stdio.h> 

int main (void) { 
    int grade; //number 0-10 associated with the letter grade 
    int valid = 0; 
    while (1) { 
     do { 
      printf("Enter the student's grade: "); 
      if (1 != (valid = scanf("%i", &grade))) {// 1 is success 
       if (EOF == valid) { 
        printf ("found EOF\n"); 
        return 0; 
       } 
       while ('\n' != getchar ()) {//clear input stream 
       } 
      } 
     } while (!valid); 
     switch (grade) { 
      case 10: printf("A \n"); break; 
      case 9: printf("A \n"); break; 
      case 8: printf("B \n"); break; 
      case 7: printf("C \n"); break; 
      case 6: printf("D \n"); break; 
      case 5: printf("F \n"); break; 
      case 4: printf("F \n"); break; 
      case 3: printf("F \n"); break; 
      case 2: printf("F \n"); break; 
      case 1: printf("F \n"); break; 
      case 0: printf("F \n"); break; 
      default: printf("Please enter a valid test score \n"); break; 
     } 
    } 
    return 0; 
} 
+0

これは本当にありがとうございます(他の人にも感謝します)これは私が混乱していたことを確認する方法を理解するのに役立ちます! – Digglit

2

scanfが成功したかどうかを確認します。任意の本のための

int nread = scanf("%i", &grade); 
if (nread != 1) // scanf failed, start cleanup 
{ 
    scanf("%*[^\n]%*c"); 
} 

見て、あなたはscanf戻り成功した要素の数がを読んで、あなたが文字を入力した場合、それは整数を読み、0を返すのに失敗することを知っているよ(何も読みません)あなたは間違ったことがあることを知り、間違ったものを捨てることができます。

エラーが発生すると何も読み込まれないので、間違ったものが入力バッファに残ってしまい、ひどく次のscanfを破損し、出力フラッシングが無限に進むことがあります。


P.S.あなただけの1にマージ、case 5 4 3...後のステートメントを繰り返す必要はありません。

case 5: // Remove these and leave the last one there 
case 4: 
case 3: 
case 2: 
case 1: 
case 0: printf("F \n"); break; 
+1

https://stackoverflow.com/questions/1694036/why-is-the -gets-function-so-dangerous-that-should-be-be-used- –

+2

'gets(wastebuf)'のより良い代替手段は 'scanf("%* [^ \ n]%* c ")です。 ' – HolyBlackCat

関連する問題