Discussion: Deciphering scanf()
Understand the use of scanf() as an input filtering function in C, including its unique format specifiers %[ and %[^] for controlled input reading. Learn why scanf() is often discouraged due to security issues and how it processes input differently from printf(). Gain insight into handling formatted input and common pitfalls associated with scanf().
We'll cover the following...
Run the code
Now, it's time to execute the code and observe the output.
#include <stdio.h>
int main()
{
char buffer[32];
printf("Type something: ");
scanf("%[ABC]", buffer);
printf("You typed: %s\n", buffer);
return(0);
}Understanding the output
The program prompts for input, but only uppercase letters ABC are allowed:
Type something: ALPHAYou typed: A
Note: Any character input other than ABC returns garbage. The word should also start with the characters given in the string (which in our case is "ABC").
The scanf() function is a formatted input function, so it’s not well suited for reading text input, though it’s often used this way in introductory programming books and ...