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
I could not reproduce your problem, but adding a
fflush(stdout);should take care of your problem.I would also change the scans to
scanf("%19s", str);. Otherwise, bad things could happen if you enter a string longer thanstrcan hold.