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*/
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 usingfgets()or an equivalent to read lines of data, and then usesscanf()– a much more civilized function – to parse the data.See also a loosely related question: SO 3591642.