Scanf trouble
5 messages in this thread
Hello Experts. Could someone save me from a fit of anger that will register on
the Richter scale please. Below I have an example function. The problem I'm
having seems small, however it appears to defy logic at least to me.
I want to use the variable Question to ask the user if the while loop is to
be repeated again. The function goes through the first time and without even
activating the scanf, terminates the program. As you can see I gave Question
the value to continue the loop right away but during debug the value shows a
linefeed value. How can I get scanf to stop and take the answer y or n?
#include <stdio.h> main () {
FILE *data;
char Question = 'y';
if (( data = fopen ("Name", "a+")) == (FILE *) NULL ){
fprintf (stderr, " Can't open database!\n");
exit (1);
}
while (Question == 'y' || Question == 'Y'){
/* Function blah blah */
/* I even tried putting Question = 'y'; or = NULL in the middle of
the while loop without luck. */
printf ("Continue y/n ? ");
scanf ("%c", &Question);
} fclose (data); } Thanks for saving my sanity…well actually you might
be too late there.
Henry
Henry,
Scanf is really a pretty evil function, especially when you're
dealing with "char" variables. I suggest using gets() or fgets()
instead. This will get a whole line at a time, terminated by a
newline. You can look at what they typed and determine what you
want to do after getting the line:
fgets(buf, sizeof(buf), stdin); // should check for error…
if(buf[0] == 'y' || buf[0] == 'Y') ….
This way works, but is a little inflexible. The next way allows
for leading white space:
fgets(…)
for(i=0; iswhite(buf[i]); i++);
if(buf[0] == 'y' || buf[0] == 'Y') …
For more complex input, look at the ANSI function strtok() which will
break the input line up into logical "tokens" seperated by white space
or whatever other seperator characters you like:
char *token, char *nexttoken;
token = strtok(buf, " \t\n");
nexttoken = strtok(NULL, " \t\n");
–Doug
Thanks for the help Doug. You aren't kidding about scanf being 'evil'. The
scanf didn't work with int's either. I finally went with a char string[0] but
will investigate your examples all the same.
Regards Henry
The main problem with scanf is that it considers a carriage return to be white
space, rather than an input terminator.
In my programs, I always use fgets to read one line, then use sscanf to parse
that line – that way I get scanf's power without it's habit of reading too far
ahead.
I would avoid strtok unless you need to get really fancy.
Thanks Michael. I like the idea of fgets and sscanf and will check it out.
Regards Henry