Difference between scanf("%[^\n]") and scanf("%s")?

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:

  1. Isn´t the behavior the same because scanf("%s") stops at trailing white space characters such as the newline character?

  2. Why should I implement scanf("%[^\n]") when scanf("%s") aleady does the same?

Thank you very much.

Upvotes: 0

Views: 307

Answers (1)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

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

Related Questions