The main reason for character classes is that the% s notation stops at the first space character, even if you specify the length of the field, and you often don't want to. In this case, the symbol class designation can be extremely useful.
Consider this code to read a string up to 10 characters long, discarding any excess, but keeping spaces:
#include <ctype.h> #include <stdio.h> int main(void) { char buffer[10+1] = ""; int rc; while ((rc = scanf("%10[^\n]%*[^\n]", buffer)) >= 0) { int c = getchar(); printf("rc = %d\n", rc); if (rc >= 0) printf("buffer = <<%s>>\n", buffer); buffer[0] = '\0'; } printf("rc = %d\n", rc); return(0); }
This was sample code for discussing comp.lang.c.moderated (circa June 2004) regarding getline() options.
At least some confusion reigns. The first format specifier %10[^\n] reads up to 10 characters other than the new line, and they are assigned to the buffer along with a trailing zero. The second format specifier %*[^\n] contains an assignment suppression character ( * ) and reads zero or more remaining characters, other than a new line, from the input. When the scanf() function completes, the input points to the next newline character. The loop body reads and prints this character, so when the loop restarts, the input looks at the beginning of the next line. Then the process is repeated. If the line is shorter than 10 characters, then these characters are copied to the buffer, and the format of "zero or no longer news lines" processes a zero that is not associated with the new line.
source share