Home > other >  Is the format specifier %[^\n]s legal in C89?
Is the format specifier %[^\n]s legal in C89?

Time:12-27

I'm reading a string from sdin with a scanf by doing:

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

%[^\n]s reads till a new line character is found. Is this legal in ANSI-C?

CodePudding user response:

You should not use this format for multiple reasons:

  • The s in "%[^\n]s" is not part of the conversion specifier, it is a plain character that scanf will try to match after the characters read from the line, at a time where the current character is either a newline or the end of file. You should remove the s.

  • scanf("%[^\n]", msg); will fail and return 0, leaving msg unchanged if the user hits enter with an empty input line.

  • scanf("%[^\n]", msg); will cause a buffer overflow for any sufficiently long input line. The maximum number of characters to store into the array pointed to by msg should be specified between the % and the [ as:

      char buf[100];
      if (scanf("           
  • Related