0

I recently saw an usage of '\n' as format specifier for scanf() function in C.

More precisely, it was:

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

And I'm just wondering how the scanf will deal with that... I'm talking about the second '\n'.

And the next question is, why won't it work for Windows text files as input? I'm pretty sure the cause is different line endings in Windows and Unix, but I don't know exactly how it causes this and I'm wondering.

Thx in advance and enjoy your day.

Dandys
  • 47
  • 1
  • 4
  • 1
    Please see [What is the effect of trailing white space in a scanf() format string?](https://stackoverflow.com/questions/19499060/what-is-the-effect-of-trailing-white-space-in-a-scanf-format-string) – Weather Vane Oct 25 '22 at 09:32
  • Because the string scan here ends at a newline, this is an attempt to clear the newline, but is quite wrong. Other formats leave the newline in the buffer too, but you don't often see them being kludged. Deal with *leading* whitespace, like this: `scanf(" %[^\n]", arr);` – Weather Vane Oct 25 '22 at 09:35
  • You can use `%[^\n]%*c` to read and discard the newline. Note that use of `%s` or `%[` without a maximum width is inherently unsafe, so you may want to set a maximum width and capture the character that should be a newline to check that it really is a newline. – Ian Abbott Oct 25 '22 at 09:47

0 Answers0