Search⌘ K
AI Features

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().

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);
}
C code for the given puzzle

Understanding the output

The program prompts for input, but only uppercase letters ABC are allowed:

Type something: ALPHA
You typed: A
Code output
...