Unable to understand - reading characters from files in C

I just started to study file processing in C and wondered if I could do the math by reading the input from the file, here is the code to read characters easily and display them on the console:

int main(void)
{
    FILE *p;
    char a, b, c, ch;

    p = fopen("numbers.txt", "a+");

    while((ch = getc(p)) != EOF)
    {
        fscanf(p, "%c %c %c\n", &a, &b, &c);
        printf("%c %c %c\n", a, b, c);
    }
    fclose(p);

    return 0;
} 

numbers.txt contains (with a space before each character):

 2 + 3
 5 + 6
 6 + 7

it turns out:

2 + 3
  + 6
  + 7

I cannot understand why the output of the first line is the same as expected, but the second and third lines have a missing character, although a new line is given after each expression in numbers.txt.

+4
source share
2 answers

An extra character is scanned at the beginning of each iteration of the loop while

while((ch = getc(p)) != EOF)

fscanf() while . cplusplus.com:

. ( ) - , .

, , (feof ferror). , , EOF .

, :

while (fscanf(p, " %c %c %c", &a, &b, &c) != EOF)

while (fscanf(p, " %c %c %c", &a, &b, &c) == 3)
+6

scanf, \n, . \n , getc .

Id getc , @BLUEPIXY :

while (fscanf(p, " %c %c %c", &a, &b, &c) == 3) {
    printf("%c %c %c\n", a, b, c);
}
+6

Source: https://habr.com/ru/post/1666142/


All Articles