简体   繁体   中英

Unable to break out of “while” loop - C

I'm trying to implement a simple while loop to let the user enter multiple marks without having to reload the application, for some reason no matter what i seem to enter it always loops.

I've looked using the debugger and it doesn't seem to accept the final scanf() asking whether to repeat itself or not.

int mark = 0;
    char grade;
    char choice = 'y';

    while(choice == 'y')
    {
        //Request input
        printf("enter a mark: ");
        scanf("%d", &mark);

        //Assess mark
        grade = assess(mark);

        //Output result
        printf("That equals ");
        printf("%c", grade);
        printf(" when graded\n");

        //Repeat?
        printf("Again?...\n");
        fflush(stdin);
        scanf("&c", &choice);
    }

I've also tried it with a do - while loop and still no joy, any idea where the problem may lie?

At least two problems:

  fflush(stdin);

is undefined - you can only flush output streams. And:

    scanf("&c", &choice);

should be:

    scanf("%c", &choice);

I think last line should be

scanf("%c", &choice);

instead of

scanf("&c", &choice);

fflush() is only defined for output streams. The comp.lang.c FAQ does not recommend using it for stdin .

Also, as others have noted, use scanf("%c", &choice); to read the choice.

Try scanf("%c", &choice); .

Note that scanf returns the number of inputs matched, so you should really check the return value. If the input does not, for som reason, map to a character, your variable might be unchanged. Before the call to scanf, set choice to something != 'y' , so that you only continue if a y is input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM