scanf considerations.


Consider the following code;

     scanf("%d", &n);
     scanf"%c", &op);

Many students have done this, only to find the program "just skips through" the second scanf.

Assume you type 45\n in response to the first scanf. The 45 is copied into variable n. When your program encounters the next scanf, the remaining \n is quickly copied into the variable op.

One foolproof approach is to always flush the buffer. This will clear any pesky \n characters.

     scanf("%d", &n);
     flushall();         /* kill any characters left in buffer */
     scanf("%c", &op);
     flushall();


I tend to use an alternative when fetching input from the keyboard. Get the entire string from the keyboard using the function gets and then sscanf into the variables. The gets function fetches the string up to and including the \n character, but it throws away the \n character.

     char s1[80];
     ....
     gets(s1); /* get an entire string from the keyboard. */
     sscanf(s1, "%s", &d);
     gets(s1);
     sscanf(s1, "%s", &op);

One big advantage of this approach is that it greatly simplifies writing to a file. Note in the following, all code to write input data to a file is the same; fprintf(f1, "%s\n", s1); which lends itself well to block copying.

     char s1[80];
     ....
     gets(s1); /* get an entire string from the keyboard. */
     fprintf(f1, "%s\n", s1);
     sscanf(s1, "%s", &d);

     gets(s1);
     fprintf(f1, "%s\n", s1);
     sscanf(s1, "%s", &op);