views:

275

answers:

6

I'm new to C programming, I come from a Java background. I was wondering why in the following code, in the while loop I have to type my input ten times and then all ten inputs are displayed. I'm trying to type something once and have it displayed right after. Then continue typing my other inputs.

#include <stdio.h>
#include <stdlib.h>
#include "Helper.h"


main(){

print(PROGRAM_INFO); //prints program name and author
print(PROMPT);

char input [100]; //array to hold input from user
int isActive = 1; //1 continue shell, 0 terminate shell
int count = 0;

while (isActive == 1 && count < 10){
    print(PROMPT);
    ++count;
    scanf("%s", input);
    print(input);


}


}
+1  A: 

Try putting a '\n' character in the print. The stream just isn't being flushed.

L. Moser
+1  A: 

after your final print statement you could probably call fflush(stdout); to flush stdout to the screen.

John Boker
+1  A: 

You need to flush STDOUT. fflush(STDOUT) should do it, added after the print.

derobert
+4  A: 

Try flushing fflush(stdout) after each print(input)

Mitch Wheat
fflush(stdout); worked fine. thank you all
yep, fflush would definitely be a better way to do it as compared to '\n'.
L. Moser
+1  A: 

by default input/output is buffered, i.e the input and output bytes are stored in a byte array before being displayed to the stream.
BUFSIZ in systems is generally a multiple of 1024.Although printf is line buffered, the buffer is flushed automatically when a newline is encountered.
fflush(stdout) causes the buffered data to be flushed to output stream which in this case is stdout. you can control buffer handling using setvbuf() function

Neeraj
Note that stdout is line buffered, so you don't need to wait for BUFSIZ characters.
Thomas Padron-McCarthy
fflush does not cause the buffered data to "be displayed on screen". It causes the stdout stream of the program to flush its buffers. *If* stdout is associated with a tty that is currently visible on the screen, then it incidentally causes text to be displayed on screen. (In other words: stdout is *NOT* the screen. Don't make that assumption.)
William Pursell
@William,thomas.. thanks for your comments edited as pointed out.
Neeraj
A: 

Your print is a copy/paste error, right? It should be printf.

And you really shouldn't print the user string directly in the format of printf.
Imagine the user types "%d%f%s\a%c" ...

The best thing to do is

printf("%s\n", input);

With the '\n' in the format, you don't need to fflush(stdout); because stdout is line buffered by default and the '\n' does one on its own.

Besides, if the user types "%d%f%s\a%c" that's what you get printed.


The best thing to do is

puts(input);

puts adds the '\n' to the output and has no problems with format strings.

pmg