First of all, scanf("%[^\n]s", &name)
must be scanf("%[^\n]", name)
as
- The
s
is not part of the %[
format specifier as people new to C often think.
- The ampersand should be removed as the name of an array decays to a pointer to its first element which is already the type that
%[
expects.
Now, to answer your question, %[^\n]
will fail if the first character it sees is a \n
. For the scanf
for studentId
, you type the number and press Enter. That scanf
consumes the number but leaves the enter character (\n
) in the input stream. Then, the scanf
for name
sees the newline character and since it's the first character that it sees, it fails without touching name
. The next scanf
fails for the same reason and the last scanf
waits for a number.
But wait! Why doesn't the last scanf
fail as well? The answer to that is certain format specifiers like %d
skip leading whitespace characters. The %[
format specifier does not.
Now how do we fix this? One easy solution would be to tell scanf
to skip whitespace characters before the %[
format specifier. You can do this by adding a space before it: scanf(" %[^\n]", name)
. When scanf
sees the space, it will skip all whitespace characters from the input stream until the first non-whitespace character. This should solve your problem.