Home > Software design >  Difference between " %[^\n]%*c" and " %[^\n]" for consecutive scanf in C
Difference between " %[^\n]%*c" and " %[^\n]" for consecutive scanf in C

Time:05-04

I've been trying to scanf multiple consecutive strings.

I know you have to eliminate the newline character and i've also been told that "%[^\n]%*c" is the RIGHT way. But in my tests, " %[^\n]" works even better because it's simpler and also doesn't go wrong if i try to feed it a newline directly, it keeps waiting a string. So far so good.

Is there any case in which "%[^\n]%*c" is the better way?

Thanks a lot!

CodePudding user response:

This format string " %[^\n]" allows to skip leading white spaces including the new line character '\n' stored in the input buffer by a previous call of scanf.

However if you will use fgets after a call of scanf with such a format string then fgets will read an empty string because the new line character '\n' will be present in the input buffer.

After a call of scanf with this format string "%[^\n]%*c" you may call fgets because the new line character will be removed.

Pay attention to that these format strings "%[^\n]%*c" and " %[^\n]%*c" have different effects. The first one does not allow to skip leading white space characters opposite to the second format string.

To make a call of scanf safer you should specify a length modifier as for example

char s[100];
scanf( "            
  • Related