简体   繁体   中英

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 printf s 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?

"\\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.

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