QP School

Full Version: Misusing scanf() in C
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Not handling newline characters left in the input buffer after using scanf().

// Incorrect
char name[50];
printf("Enter your name: ");
scanf("%s", name);
// If the user enters "John Doe", the newline character is left in the buffer

// Correct
char name[50];
printf("Enter your name: ");
scanf("%49[^\n]", name);
// The format specifier reads up to 49 characters or until a newline character