When you prompt user with the first scanf
here
char opt;
scanf(" %c", &opt);
When the user enters a character, say A
, "A\n" is placed in the buffer, \n
coming from the user hitting the return key. The scanf
takes one character as requested with the " %c"
format string, and leaves the \n
on the buffer.
When the second scanf
is executed as
printf("Please Enter a New Name:");
char name[200];
scanf("%[^\n]s", name);
the format string "%[^\n]s"
requests it to read until a \n
is encountered, mind you, your buffer already contains a \n
as the first character, hence scanf
returns without reading anything, still leaving the \n
in the buffer.
When the third scanf
is executed as:
printf("Please Enter a New Code:");
char code[200];
scanf("%s", code);
(Corrected after the comments of chqrlie)
The format string "%s"
ignores the leading whitespaces, hence now the \n
is ignored, and scanf
happily waits for your input.
Notice the leading space in the format string " %c"
, the space is there to get scanf
ignore the leading whitespace, you can implement the same logic with your second scanf
. You can either ensure that all consecutive scanf
ignore the \n
left in the buffer, which turns out most format specifiers do, or you can ensure that no scanf
leaves it to begin with with using something like "<...>%*c"
to get rid of it. Though none of which are reliable and consistent methods, and as said countless times, scanf
is not designed to perform such tasks like taking user input, and you should seek alternative methods.
Also, the s
in "%[^\n]s"
certainly doesn't do what you expect. man page of the scanf
states that
An ordinary character (i.e., one other than white space or '%'). This character must exactly match the next character of input.
If it matches, scanf
discards it and continues parsing according to the remaining format specifiers. If it doesn't, scanf
stops there and returns. Since it is at the end of your format string, it returns either way, hiding a potential bug from you.