Question

I'm teaching myself C. My background is Java. I'm writing a simple console app that is supposed to prompt the user for a number, and then tell the user what number he printed, and then prompt him for another number. The program exits if the user types in 0.

My code is not behaving the way I expect it to. This is the code:

#include <stdio.h>

int main() {
    while (1) {
        printf("Please enter a number: ");
        int this_is_a_number = 0;
        scanf("%d", &this_is_a_number);
        printf("You entered %d\n", this_is_a_number);
        if (this_is_a_number == 0) {
            break;
        }
        getchar();
    }
    return 0;
}

When the program starts, it doesn't prompt me for a number. It does let me type one in. After hitting return, it lets me type in another, and so on and so forth until I return 0. Then it prints out everything that it was supposed to print out earlier, and then exits.

So for example, if I start the program and then type 7, 8, 9, and 0, hitting return after each one, the console should look like this:

Please enter a number:
7
You entered 7
Please enter a number:
8
You entered 8
Please enter a number:
9
You entered 9
Please enter a number:
0
You entered 0

But instead, it looks like this:

7
8
9
0
Please enter a number:
You entered 7
Please enter a number:
You entered 8
Please enter a number:
You entered 9
Please enter a number:
You entered 0

What am I not understanding about flow in C?

Was it helpful?

Solution

This is probably caused by the fact that the output is buffered. Try to flush the buffer after each printf with fflush, eg:

printf(...);
fflush(stdout);
scanf(...);

You can even directly disable buffering through setbuf(stdout, NULL).

OTHER TIPS

You understand the flow control perfectly. You just don't understand what printf and scanf do.

The first problem, that the output from printf is delayed, is because the standard IO library uses buffering. That is, printf doesn't actually perform the expensive operation of writing the data to a terminal until it feels like it, or you tell it to. In this case, fflush is your friend:

printf("Please enter a number: ");
fflush(stdout);

The second problem, that getchar() isn't waiting for your input, is related to scanf. scanf only reads the characters that are required to form its argument -- in this case, an integer. It leaves all of the other characters in the input stream. So, when you type "79" followed by a newline, scanf reads the 7, reads the 9, and leaves the newline in the input stream. Subsequently getchar consumtes that newline, and doesn't wait for anything.

The solution to the second problem is probably just getting rid of the getchar() altogether.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top