First of all, avoid scanf() . Using it is not worth the pain.
See: Why does everyone say not to use scanf? What should i use instead?
Using a space character in scanf() will ignore any number of whitespace left in the input stream, what if you need to read more inputs? Consider:
While 3rd scanf () can be fixed in the same way using leading spaces, it will not always be as simple as above. Another serious problem: scanf() will not discard the input stream in the input stream if it does not match the format. For example, if you enter abc for int , for example: scanf("%d", &int_var); then abc will have to read and discard. Consider:
#include <stdio.h> int main(void) { int i; while(1) { if (scanf("%d", &i) != 1) { /* Input "abc" */ printf("Invalid input. Try again\n"); } else { break; } } printf("Int read: %d\n", i); return 0; }
Another common problem is mixing scanf() and fgets() . Consider:
#include <stdio.h> int main(void) { int age; char name[256]; printf("Input your age:"); scanf("%d", &age); /* Input 10 */ printf("Input your full name [firstname lastname]"); fgets(name, sizeof name, stdin); /* Doesn't read! */ return 0; }
The fgets() call does not wait for input because the newline left by the previous scanf () call is read, and fgets () completes the data entry when it encounters a new line.
There are many other similar problems related to scanf() . This is why it is generally recommended to avoid this.
So what is the alternative? Use fgets() as follows to read a single character:
#include <stdio.h> int main(void) { char line[256]; char ch; if (fgets(line, sizeof line, stdin) == NULL) { printf("Input error.\n"); exit(1); } ch = line[0]; printf("Character read: %c\n", ch); return 0; }
One detail to consider when using fgets() will be to read a newline if there is enough space in the inut buffer. If this is not desired, you can remove it:
char line[256]; if (fgets(line, sizeof line, stdin) == NULL) { printf("Input error.\n"); exit(1); } line[strcpsn(line, "\n")] = 0;