-1

C language doesn't scan variable after reading that variable as string(or char) instead of integer But the most weird is that it is entering in infinite loop


int main( ){
    int answer;
    printf("Hello\n");

    while (answer != 3){
        scanf("%d",&answer);
        switch (answer) {
            case 3:
                break;
            default:{
                printf("Invalid input\nTry again\n\n");
                break;}
        }
    }

    return 0;
}

To find how C language works and fix the problem

Mihai
  • 11
  • 6

1 Answers1

0

You can add one more statement under the label default to avoid an infinite loop when a non-number is entered

        default: {
            printf( "Invalid input\nTry again\n\n" );
            scanf( "%*[^\n]" );
            break; }
        }

If the user will try to interrupt the input you can also write

if ( scanf("%d",&answer) == EOF ) break;

to exit the while loop.

Pay attention to that the variable answer shall be initialized before the while loop.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • But why it doesn't read my first scanf. It is only for my better understanding – Mihai Mar 07 '23 at 20:58
  • 1
    @Mihai I have not understood what you mean by the first scanf. If you enter a non-number then it is stored in the input buffer and you need to skip it. Otherwise a next call of scanf will try to read that non-number with the same result and you will have an infinite loop. – Vlad from Moscow Mar 07 '23 at 20:59
  • Если ты разговариваешь на русском пожалуйста объясни почему при вводе строки просто перестает читать scanf. Тоесть объясни как именно происходит процесс для понимания.Еще раз спасибо за решение проблемы и если что не злись на мои тупые вопросы) – Mihai Mar 07 '23 at 21:10
  • @Mihai Если вы ввели не число, то оно не читается и остается во входном буфере. Следующий вызов scanf снова сталкивается с этим не числом и не может его прочитать, и в результате получается бесконечный цикл. – Vlad from Moscow Mar 07 '23 at 21:13
  • Значи при втором scanf он опять читает из буфера и не может прочесть и вы просто создали scanf который может прочесть из буфера. Огромное вам спасибо – Mihai Mar 07 '23 at 21:19