int m" /> int m" /> int m"/>

printf is not working as expected. Can someone explain the output?

98 views Asked by At

I am trying to read two strings from the keyboard and print them. Why does printf("read 1st\n") run after the second scanf()?

#include <stdio.h>

int main(void)
{
    char str[20];
    char str2[20];

    scanf("%s", str);
    printf("read 1st\n");
    scanf("%s", str2);
    printf("read 2nd\n");

    printf("str: %s\nstr2: %s\n", str, str2);

    return 0;
}
Expected:
foo
read 1st
bar
read 2nd
str: foo
str2: bar

Actual:
foo
bar
read 1st
read 2nd
str:foo
str2:bar
1

There are 1 answers

0
klutt On

I could not reproduce your problem, but adding a fflush(stdout); should take care of your problem.

scanf("%s", str);
printf("read 1st\n");
fflush(stdout); // Ensures that the above is printed before scanf is executed
scanf("%s", str2);
printf("read 2nd\n");

I would also change the scans to scanf("%19s", str);. Otherwise, bad things could happen if you enter a string longer than str can hold.