tags:

views:

108

answers:

2

I am working on a simple application written in C. I am working in a Unix environment.

My application is doing some simple I/O. I use printf to prompt the user for some input and then use scanf to get that input.

The problem is, I don't know how to tell my application that I am ready to proceed after entering in a value. Typing 'enter' provides a newline '\n' which makes sense. Control-d does allow scanf to capture my input but seems to ignore any subsequent scanf instructions.

Can someone help me out?

printf("Enter name\n");
scanf("%s",input);
printf("%s",input);

printf("enter more junk\n")
scanf("%s",morestuff); /* cntrl+d skips this*/
+2  A: 

Check the return value from scanf(). Once it has gotten EOF (as a result of you typing control-D), it will fail each time until you clear the error.

Be cautious about using scanf(); I find it too hard to use in the real world because it does not give me the control over error handling that I think I need. I recommend using fgets() or an equivalent to read lines of data, and then use sscanf() - a much more civilized function - to parse the data.

See also a loosely related question: SO 3591642.

Jonathan Leffler
perfect. Thanks.. The problem was a newline char in the scanf. i will look into these other functions you mentioned.
Nick
Jonathan is being charitable when he says "Be cautious about using scanf()"; I would instead go with "avoid it like the plague" :-) The naive use of scanf (%s format with no field width limit) is a buffer overflow bug waiting to happen.
David Gelhar
A: 

[EDIT: This answer is incorrect, as I stated below, I'm learning as well]

Have you tried CTRL-Z?

That sends EOF to scanf, which, according to its man page, should make scanf move to the next field. As you've entered only a string as the input format, that should terminate the scanf.

I can't test this right now, but you can give it a shot.

Man page is here:

http://www.slac.stanford.edu/comp/unix/package/rtems/doc/html/libc/libc.info.scanf.html

babbitt
The normal default value for sending EOF from a terminal on Unix is Control-D; on DOS, it is Control-Z. You can set Unix to mimic DOS with '`stty eof ^Z`', of course. However, more typically, Control-Z is used to suspend the current (foreground) process and let you do things with the shell.
Jonathan Leffler
Thanks, always happy to learn something new (or in this case, re-learn something).
babbitt