Previous note, the s
should be removed, it's not part of the specifier and is enough to mess up your read, scanf
will try to match an s
character against the string you input past the 40 characters, until it finds one the execution will not advance.
To answer your question using a single getchar
is not the best approach, you can use this common routine to clear the buffer:
int n = scanf(" %40[^\n]", title);
int c;
while((c = getchar()) != '\n' && c != EOF){}
if(c == EOF){
// in the rare cases this can happen, it may be unrecoverable
// it's best to just abort
return EXIT_FAILURE;
}
//...
Why is this useful? It reads and discards all the characters remaing in the stdin
buffer, regardless of what they are.
In a situation when an inputed string has, let's say 45 characters, this approach will clear the stdin
buffer whereas a single getchar
only clears 1 character.
Note that I added a space before the specifier, this is useful because it discards all white spaces before the first parseable character is found, newlines, spaces, tabs, etc. This is usually the desired behavior, for instance, if you hit Enter, or space Enter it will discard those and keep waiting for the input, but if you want to parse empty lines you should remove it, or alternatively use fgets
.