I have to read a series of input from a file using scanf. But there are different outcomes in 2 situations. Code1- Reading an integer and a char array.
char plaintext[20];
int started = 0;
int x;
while (scanf("%i,%19[^\n]",&x,plaintext) == 2)
{
if (started == 1)
printf(",\n");
else
started = 1;
printf("i read a line from a file");
}
printf("\n");
This works perfectly fine. The scanf reads every line in the file and the printf() outputs the required line for each line input.
Code2-Reading only a char array
char plaintext[20];
int started = 0;
while (scanf("%19[^\n]",plaintext) == 1)
{
if (started == 1)
printf(",\n");
else
started = 1;
printf("i read a line from a file");
}
printf("\n");
Here, the scanf reads only the first line and prints "i read a line from a file" only once.Why??
One solution is using %*c in scanf in Code 2. But why Code 1 works fine, but not Code 2.
"%19[^\n]"-->"%19[^\n]%*c"