Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

User Input 1

Status
Not open for further replies.

bitwise

Programmer
Mar 15, 2001
269
US
What is the proper way to do user input in C?

Here is my problem. When I do a scanf("%10s", buffer); if the user types more than 10 characters the remaining characters on stdin will be used for the next call to scanf. This is also the case when using getchar(). This is very annoying because I don't want the input from the first input prompt to override input for the second input prompt. Is there a way to clear the stdin stream so that another read from stdin doesn't use the remaining data on stdin?

Thanks,
-bitwise
 
There are 2 ways that I know of, these are:

(1) insert the following code after the scanf:
while (getc (stdin) != '\n');

i.e. getc will continue to pull the remining characters from the stdin buffer until the 'end of line' character is received.

(2) use the fflush library function to 'flush' the stdin buffer (inserted after the scanf):
fflush (stdin);

I typically use the first option, and implement it using a #define,i.e.
#define FLUSH while (getc (stdin) != '\n')

and then your code would read a bit easier.

cheers,
Barrie
 
Thanks barriee. The fflush(stdin) doesn't work I had tried that method already. I figured the only way was to manually loop through the rest of the input. Thanks for confirming that!

-bitwise
 
You'll want to change that loop to check for EOF, in case the user signals EOF before pressing Enter:

int gobble_stdin(void)
{
int c;
while ((c=getchar())!='\n' && c!=EOF)
;
}

In C, there isn't any defined behavior when fflush() is used on input streams. However, implementations are free to define fflush(stdin) to discard input characters remaining in the input stream. Last time I checked, this is how MS defines it in VC++, which may explain the widespread misconception about the behavior of this function.
Russ
bobbitts@hotmail.com
 
Status
Not open for further replies.

Similar threads

  • Locked
  • Question
Replies
4
Views
127
Replies
3
Views
176
Replies
3
Views
112
Replies
10
Views
175
Replies
2
Views
84

Part and Inventory Search

Sponsor

Back
Top