QP School
Misusing scanf() in C - Printable Version

+- QP School (https://qomplainerzschool.lima-city.de)
+-- Forum: Tutorials (https://qomplainerzschool.lima-city.de/forumdisplay.php?fid=3)
+--- Forum: C 18 Tutorials (https://qomplainerzschool.lima-city.de/forumdisplay.php?fid=32)
+--- Thread: Misusing scanf() in C (/showthread.php?tid=5120)



Misusing scanf() in C - Qomplainerz - 07-26-2023

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