Originally Posted by
gemera
Code:
char buff[100];
scanf("%99[^\n]%*c",buff);
I hate this format string. It consumes the input, but doesn't always indicate success:
%99[
This indicates that you will match whatever is in the brackets (up to 99 bytes)
^
Then you invert that logic and say match everything except what's in the brackets
\n]
%*c
Then you discard the next byte without assigning it.
So you should always get 1 if the scanf function reads something. But that doesn't happen, because %[ has to match something in the input to count. If you have a blank line in your input though, this happens:
Code:
#include <stdio.h>
int main(void)
{
char dummy[100] = "";
const char* blankln = "\n";
int value = sscanf(blankln, "%99[^\n]%*c", dummy);
printf("value: %d\n", value);
return 0;
}
#if 0
output:
value: 0
http://codepad.org/2z9qySfp
#endif
It's so broken.
So no, scanf does not imitate fgets(). It would be better to roll your own function using getchar() if you have to. In fact, it can be a nice approach - another forum member used it to implement the POSIX function getline() here.