Reputation: 137
I'm new to programming in c++ and I'm facing a problem following lynda.com tutorials. It seems okay on the tutorial video but this isnt working with me.
#include <stdio.h>
enum { max_string = 127 };
static char string[max_string + 1 ] = "";
int main( int argc, char ** argv ) {
printf("Type a string: ");
fgets(string, max_string, stdin);
printf("The string is %s", string);
return 0;
}
And when I run this something blank appears and I need when I right something like "hey" in the blanket space, this happens:
hey
Type a string: The string is hey
This is completely strange for me and I have no idea what Im doing wrong tbh. I'm using Eclipse btw.
Could someone help me out?
Upvotes: 0
Views: 229
Reputation: 263657
It appears that your standard output stream is line-buffered, meaning that text you print doesn't appear until you've printed a complete line. It should be unbuffered if you're writing to an interactive device; perhaps something is preventing the system from being aware that the output device is interactive.
Adding
fflush(stdout);
after your first printf
should force the "Type a string: "
prompt to appear immediately (and even if your output is unbuffered, fflush(stdout)
is harmless).
I was about to suggest changing your second printf
from:
printf("The string is %s", string);
to:
printf("The string is %s\n", string);
to ensure that your program's output ends with a newline (some systems can misbehave if it isn't) -- but fgets()
actually leaves the newline in your string (unless the input line was very long). Eventually you'll want to be able to deal with that kind of thing.
Upvotes: 2