Joy Ram Sen Gupta
Joy Ram Sen Gupta

Reputation: 405

How does scanf(" %[^\n]", str); work in C Programming?

I encountered this in a C program:

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

Please explain how it works and why?

Upvotes: 7

Views: 47307

Answers (2)

user824425
user824425

Reputation:

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);

Upvotes: 12

Atal Kishore
Atal Kishore

Reputation: 4738

[^\n] searches for line break

hence it will scan for the string until enter is pressed

Upvotes: 2

Related Questions