Reputation: 15032
I have read about the behavior of scansets. By studying and testing, I encountered an issue.
Doesn´t scanf("%[^\n]")
behave the same like scanf("%s")
?
scanf("%s")
is consuming characters until a white space character such as the \n
-character is found in stdin
. So the result should be exactly the same as scanf("%[^\n]")
.
For example:
char str[100];
scanf("%99[^\n]s", str);
In comparison to:
char str[100];
scanf("%99s",str);
So my Questions are:
Isn´t the behavior the same because scanf("%s")
stops at trailing white space characters such as the newline character?
Why should I implement scanf("%[^\n]")
when scanf("%s")
aleady does the same?
Thank you very much.
Upvotes: 0
Views: 307
Reputation: 215201
You seem to be under the mistaken impression that scanset is some sort of modifier to %s
, as evidenced in your example:
scanf("%[^\n]s", str);
This is a scanf format string that will always fail matching the literal 's'
at the end.
Rather, %[
is a completely different conversion specifier from %s
. %s
consumes and ignores any initial whitespace before starting, then stops at whitespace. %[
does not ignore leading whitespace at all and only stops at a non-matching character — it does not treat whitespace specially.
Upvotes: 3