#Scanf trouble
05-Apr-93 16:33:40
Sb: #33899-#Scanf trouble
Fm: Doug Walker 71165,2274
To: Henry Williams 73527,1446
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