How do you scanf several words (with spaces in between and an arbitrary number) into a string and not get the '\n' character in the end? I know similar questions has been asked but none of them gave a really satisfying answer. I hope to get an answer to achieve such mechanism in one statement.
Asked
Active
Viewed 199 times
1 Answers
3
char buffer[256];
if (scanf(" %255[^\n]", buffer) != 1)
…oops — EOF or something dramatically awry…
The scan set doesn't skip leading white space (neither does %c
or %n
), so I added the leading blank to skip leading white space. If you want the leading spaces too, drop that space in the format string, but the onus is on you to ensure that the next character in the input is not a newline (which it often will be if you've just read a number, for example). The conversion (scan set) stops when a newline is reached, or at EOF, or when 255 characters have been read. You could add %*[\n]
to read the newline if the next character is a newline. You won't ever know whether that matched or not, though. If you must know, you need:
char buffer[256];
char nl[2];
int rc;
if ((rc = scanf(" %255[^\n]%[\n]", buffer, nl)) <= 0)
…oops — EOF or something dramatically awry…
else if (rc == 1)
…no newline — presumably the input line was longer than 255 characters…
else
…data in buffer is a complete line except for the newline, but the newline was read…
Note the use of 255 vs 256 — that is not an accident but is 100% necessary.

Jonathan Leffler
- 730,956
- 141
- 904
- 1,278
-
`char nl; .... " %255[^\n]%[\n]", buffer, &nl` is a problem as 2+ characters are written. Suggest `char nl[2]; .... " %255[^\n]%1[\n]", buffer, nl` – chux - Reinstate Monica Jul 15 '18 at 04:53
-
Brain in 'fried mode' — fixing (code; not brain — that's a lost cause!). – Jonathan Leffler Jul 15 '18 at 04:55
-
Note that this approach fails when a line consists of only `"\n"` as that is consumed by `scanf(" %255[^\n]%[\n]",...` and looks to the next line. – chux - Reinstate Monica Jul 15 '18 at 04:55
-
Assuming there is no leading blank in the format, the scan set does not accept zero characters as valid. So, if the next character is a newline (an empty line), the first scan set fails and the return value from `scanf()` is `0` – not EOF, but a complete matching failure. If the leading blank is there, the input is looking for the first line that contains at least one non-white-space character. The alternative is to use `fgets()` or POSIX `getline()`, but this may be usable as part of a longer format string. As always, it all depends on what you're after. The `scanf()` function is tricky! – Jonathan Leffler Jul 15 '18 at 05:01
-
Yes `scanf()` is tricky. `scanf(" %255[^\n]%[\n]"....` with input `"abc\n\n"`, will attempt to write outside the bounds of `char nl[2];`. With input `"abc\n", the function will block and not return until some non `'\n'` is read after the `'\n'`. – chux - Reinstate Monica Jul 15 '18 at 19:46