Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C language doesn't scan variable

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){
        start();//It is declared above
        scanf("%d",&answer);
        switch (answer) {
            case 1:{
                showCenters();//Also declared
                break;}
            case 3:{
                break;}
            default:{
                printf("Invalid input\nTry again\n\n");
                break;}
        }
    }

    return 0;
}

To find how C language works and fix the problem

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading