Jamie Keeling
Jamie Keeling

Reputation: 9966

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?

Upvotes: 1

Views: 967

Answers (4)

gnud
gnud

Reputation: 78528

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.

Upvotes: 1

David
David

Reputation: 1187

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.

Upvotes: 1

anon
anon

Reputation:

At least two problems:

  fflush(stdin);

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

    scanf("&c", &choice);

should be:

    scanf("%c", &choice);

Upvotes: 8

Eimantas
Eimantas

Reputation: 49344

I think last line should be

scanf("%c", &choice);

instead of

scanf("&c", &choice);

Upvotes: 3

Related Questions