tags:

views:

272

answers:

4

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?

+3  A: 

I think last line should be

scanf("%c", &choice);

instead of

scanf("&c", &choice);
Eimantas
+7  A: 

At least two problems:

  fflush(stdin);

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

    scanf("&c", &choice);

should be:

    scanf("%c", &choice);
anon
`fflush(stdin)` is also bad in situations where the operation *is* defined, since it will break batch processing, e.g. `grader < listofgrades.txt > results.txt`.
Ignacio Vazquez-Abrams
It's never defined - that's the point.
anon
Jamie Keeling
fflush(stdout), yes, it's very frequently used.If you want to print out anything without putting a newline at the end (say, updating a progress meter), you need to fflush(stdout) to have the new data to appear.fflush(stdin) - nope, no real sense.
SF.
+1  A: 

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.

David
+1  A: 

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.

gnud