Xeos
Xeos

Reputation: 6497

C - printf() after scanf() not printing until next scanf()

I am trying to read first character in each line of the input and then based on the first character, determine which format the rest of the line is in. Then I use scanf() to read the values according to the command received.

char name[50];
int rating, ref;

int main() {
    int command;
    while (command = getchar()) {
        if (command == EOF || command == '\0') break;
        if (!processCommand(command)) break;
        printf("done processing, waiting for new command\n");
    }
}

char processCommand(int command) {
    switch (command) {
        case 'a':
            printf("starting\n");
            if (scanf(" %s %d %d\n", name, &rating, &ref) != 3) return 0;
            // SOME PROCESSING
            printf("done\n");
            break;
        default:
            exit(EXIT_FAILURE);
    }
    return 1;
}

The problem is that the output looks like this:

./program.out
a Test 5 12345
starting
a Testing 0 23456
done
done processing, waiting for new command
starting

Basically the printfs are not getting flushed to the stdout until the next processCommand() is called. I've tried all of these:

fflush(stdin);
while ( getchar() != '\n' );
fflush(stdout);
setbuf(stdout, NULL);
setvbuf(stdout, NULL, _IONBF, 0);

And none of them change anything in the output. What am I doing wrong here?

Upvotes: 3

Views: 8300

Answers (1)

chux
chux

Reputation: 153498

"\n" in if (scanf(" %s %d %d\n" prevents scanf() from returning until non-white-space is entered after the 2nd int.

"\n" does not simply scan in a '\n', It scans in all white-space until another non-white-space occurs. This usually involves a 2nd line of text as user input is line buffered.

Drop the '\n' at the end of " %s %d %d\n".

Better yet, read using fgets() and drop using scanf(). Use sscanf(), strtok(), strtod(), etc. instead.

Upvotes: 7

Related Questions