-1

What is the difference between

scanf(" %[^\n]", str_1);

and

scanf("%[^/n],str_2);

I am trying to read a full line as an input using scanf function, the first one works fine but as soon as I remove the space between " and % the function takes no input.

Ðаn
  • 10,934
  • 11
  • 59
  • 95
epicure
  • 7
  • 1
  • `/n` is a literal string `/n` while `\n` is a new line. And don't tag both C and C++, they're different languages – phuclv Apr 05 '21 at 03:11
  • Use `fgets()`. `scanf(" %[^\n]",` without a width limit is worse than [`gets()`](https://stackoverflow.com/questions/1694036/why-is-the-gets-function-so-dangerous-that-it-should-not-be-used) – chux - Reinstate Monica Apr 05 '21 at 03:17

1 Answers1

2
scanf(" %[^\n]", str_1);

This will skip whitespace (until it finds a non-whitespace character) and then start reading characters into str_1 until it reaches a newline or EOF. It will not do any bounds checking, so may overflow the storage for str_1. If an EOF is read before finding a non-whitespace character, it will return 0 without writing anything into str_1 (not even a NUL character).

scanf("%[^/n],str_2);

This will read characters other than / and n into str_2 until it sees either a / or n or an EOF. Like the first one, it does not do any bounds checking so may (will likely?) overflow the storage of str_2. If the first character of input is either a / or a n (or EOF) it will fail to match the pattern at all, returning 0 and not storing anything into str_2 (not even a NUL terminator).

Basic scanf semantics -- whitspace in the format string will skip 0 or more whitespace characters in the input until a non-whitespace character is reached to start whatever the next pattern is. %[ matches characters with no bounds checking, so should never be used with untrusted input -- you should always use an explicit bound or m modifier.

If you want to read lines of input (as opposed to whitespace delimited words, ignoring differences between newlines and other whitespace), you should use fgets or getline

Chris Dodd
  • 119,907
  • 13
  • 134
  • 226