7

I encountered this in a C program:

char str[100];
scanf(" %[^\n]", str);

Please explain how it works and why?

Cyril Graze
  • 3,881
  • 2
  • 21
  • 27
Joy Ram Sen Gupta
  • 365
  • 1
  • 6
  • 16
  • this means scan everything till you encounter `Enter` means newline character – sinsuren Oct 14 '16 at 08:32
  • 3
    A good source for answers is the [documentation](http://www.cplusplus.com/reference/cstdio/scanf/), which has explanations of the supported format specifiers – UnholySheep Oct 14 '16 at 08:33

2 Answers2

11

This scanf format string consists of two parts:

  • a space character, which skips space characters (' ', '\t', '\n', etcetera) in the input, and
  • the %[^\n] conversion specification, which matches a string of all characters not equal to the new line character ('\n') and stores it (plus a terminating '\0' character) in str.

Note however that if the input (after the leading spaces, and before the first newline character) is longer than 99 characters, this function exhibits undefined behaviour, because str can only hold 100 chars including the terminating '\0' character. A safer alternative is:

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

[^\n] searches for line break

hence it will scan for the string until enter is pressed

Atal Kishore
  • 4,480
  • 3
  • 18
  • 27