I’ve got a question about how the scanf function works. In this program:
#include <stdio.h>
int main(void) {
int x;
char y;
printf("Write a number: ");
scanf("%d", &x);
printf("Write a character: ");
scanf(" %c", &y);
printf("%d", x);
printf("%c", y);
return 0;
}
If the user writes a number then hit enter then the scanf function would see from the format string that is should expect a number. When the user taps enter it would not read the new-line character and put it back in the buffer. Then since I am reading a character next I need to have a whitespace in the format string because the scanf function would otherwise take the new-line character and put in the y-variable.
However I am just curious about what happened if the user wrote something like
j344lk4fjk388
Would it put everything back in the buffer? And everything that gets “put-back” in the buffer would it automatically be read by the next scanf function in my program?
I’m reading: C Programming A Modern Approach 2nd Edition
You should always check the return value from
scanf()to ensure that all the conversions you expected were successful.Given the sample input:
The first
scanf()would fail becausejcannot be converted to an integer – returning 0 for the number of successful conversions. The second call would succeed, returning ‘j’ as the character.If you need the string to be treated as an integer, use
fgets()or a relative (perhaps POSIXgetline()) to read the string, thenstrtoul()(or the appropriate relative –strtol(),strtoll(),strtoull(),strtoimax()orstrtoumax()), specifying a base of at least 21 to convert the ‘j’, or 23 to take the ‘l’ and ‘k’.