1

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
alk
  • 69,737
  • 10
  • 105
  • 255

1 Answers1

1

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.

klutt
  • 30,332
  • 17
  • 55
  • 95