0

While Trying this code on eclipse CDT with GCC 5.1.0 Compiler All the strings were printed after the user input .. and while compiling it on Visual Studio and Code Blocks IDEs even with the windows CMD The program worked just fine as expected ..


‪#‎include‬ <stdio.h>
static char string[128] = "";
int main() {
printf("Type a string: ");
scanf("%s",string);
printf("The String is %s", string);
return 0;
}

Eclipse Output:

enter image description here


Visual Studio Output:

enter image description here

Thanks ,,,

underscore_d
  • 6,309
  • 3
  • 38
  • 64
Mr-Eyes
  • 27
  • 1
  • 6
  • So Eclipse has an integrated editor… and VS started your program which ran in a console. What's the problem, again?` – Columbo Jul 29 '15 at 16:26
  • What is the problem? If by "unexpected output" you mean the implicit `pause` command inserted by your IDE, then that's not a problem (how else would you see the output, if the window closed immediately?). And why is this tagged `c++`? It does not appear to be using any C++ features. – underscore_d Jul 29 '15 at 16:27
  • The problem described above , the sequence of running the code is not the same in the two IDEs ,, Eclipse asks me first to input the string -->> scanf then printing out all the printf . While VS is doing it correctly – Mr-Eyes Jul 29 '15 at 16:29
  • 1
    Don't forget to `fflush();` – chux - Reinstate Monica Jul 29 '15 at 16:38

1 Answers1

2

OK, I see now. I think the issue is that whenever you want to be certain that something is printed by a given point in the code, you need to flush stdout at that point.

Otherwise, streamed contents can be queued and delivered in an implementation-dependent way (usually in small batches)

The C standard library's printf(), when outputting to stdout and encountering a newline \n, provides an implicit flush, so you don't need to call flush() yourself. Whereas with C++'s std::cout, only std::endl has this property; \n is not guaranteed to.

Deliberately flushing stdout in C can be done like so: fflush(stdout);

See also: Why does printf not flush after the call unless a newline is in the format string?

Community
  • 1
  • 1
underscore_d
  • 6,309
  • 3
  • 38
  • 64