0

I am going through one small code where I need to take whole line as input through scanf function, and I think there is one format specifier "[^\n%*c]" can someone please tell me syntax for it and how it works?

4
  • 4
    The format specifier you show isn't complete, or even correct. Better use fgets if you want to read whole lines, it's much simpler (and assuming correct arguments won't lead to buffer overflows). Commented Aug 15, 2021 at 15:00
  • int result = scanf(" %99[^\n]", string); where 99 is the string size -1, and it leaves the newline in the input buffer. The leading space before % is to consume previous whitespace. The result is the number of successful conversions. It is generally poor practice to try to eat subsequent whitespace. Commented Aug 15, 2021 at 15:02
  • You can find the "syntax and how it works" here. Commented Aug 15, 2021 at 15:05
  • 1
    scanf() is not the proper tool for the job. It can do it, just like an hammer can be used to drive a screw in :-) Commented Aug 15, 2021 at 15:09

2 Answers 2

1

The best way is probably to use fgets.

char str[20];
fgets(str, 20, stdin);
printf("%s", str);

No reason to use scanf here. Just remember that fgets also puts the newline character in the buffer. It can be removed like this:

str[strcspn(str, "\n")] = 0;
Sign up to request clarification or add additional context in comments.

Comments

0
#include <stdio.h>
int main()
{
   char str[20];
   scanf("%19[^\n]%*c", str);
   printf("%s\n", str);
 
   return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.