-2

I am using Eclipse (the latest version) along with Cygwin GCC (I have also observed the same issue while using MinGW GCC, and hence changed the GCC). Consider a simple code snippet:

   #include<stdio.h>
int main(){
    char a[5];
    printf("prompt1\n");
    scanf("%s",a);
    printf("\Hi\t%s",a);
}

The image shows the entire output of the program, which, as you can see, should be in a completely different order. This issue was also on my old laptop (same version of Eclipse, with MinGW). However, I have (obviously) never come across this issue on an older version of Eclipse. (The snippet has a different prompt text..but you get the jist of it)

EDIT: also occurs with the gets() function (but gets, and scanf are obviously displayed in the correct sequence)

coder123
  • 25
  • 9
  • You have a typo here: `printf("\Hi\t%s",a);`. The first backslash is probably unintended. – walnut Sep 02 '19 at 16:36
  • notwithstanding that, the error persists.. the image in the post doesn't have that additional backslash – coder123 Sep 03 '19 at 12:27
  • I did not intend for it to solve the problem, but the backslash will cause other issues. Your question was already answered below. – walnut Sep 03 '19 at 12:33

2 Answers2

0

printf uses stdout, it's a buffered file stream. It means, it sends data to the output after its internal buffer is full (the buffer size is 512 bytes or some another value). To dump data to the console immediately, use the function fflush before scanf.

#include<stdio.h>
int main(){
    char a[5];
    printf("prompt1\n");
    fflush(stdout);
    scanf("%s",a);
    printf("Hi\t%s",a);
}
273K
  • 29,503
  • 10
  • 41
  • 64
0

I saw another SO post where Cygwin didn't flush stdio when needed. Adding the following line before the scanf call should fix it.

fflush(stdout);
jmq
  • 1,559
  • 9
  • 21
  • that does resolve it however, I also found the error while using MinGW (on another system) it also doesn't occur on an older version of Eclipse CDT on another system or in linux (i don't know which compiler each of these use though) – coder123 Sep 03 '19 at 12:30
  • @coder123 It is not related to the compiler, it depends on whether the output is going to an interactive terminal or not, see https://stackoverflow.com/a/4201325/11941443 and the rest of that question – walnut Sep 03 '19 at 12:47