Home > Blockchain >  Why can't I use "%[^\n]" scanset on my c program?
Why can't I use "%[^\n]" scanset on my c program?

Time:09-16

I'm trying to get user input for my string with spaces on my program but for some reason %[^\n] doesn't work. The "%" part is marked red. I couldn't understand why. It just skips and doesn't ask for user input. Also, this is my first question on this site. Thank you to whoever can answer my question.

int prelim, midterm, semiFinal, final, totalScore, yearLevel, studentId;
float averageScore = 0;
char name[25], degree[25];

printf("Enter your student id: ");
scanf("%d", &studentId);
printf("Name: ");
scanf("%[^\n]s", &name);
printf("Degree: ");
scanf("%[^\n]s", &degree);
printf("Year: ");
scanf("%d", &yearLevel);

CodePudding user response:

First of all, scanf("%[^\n]s", &name) must be scanf("%[^\n]", name) as

  1. The s is not part of the %[ format specifier as people new to C often think.
  2. 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.

  • Related