Search code examples
cfgetc

Storing separate characters while looping with fgetc()


So I have been trying to go trough .txt file character by character using fgetc(). I want to store the first and the third character into two seperate variables. This is an example input file. What I want to do in this case is to store the first character (6) to variable1 and the third (7) to variable2. The second one is whitespace so I´d like to skip it while looping trough the file. I am able to get the first character but can´t seem to find a way to jump to the third one and store it in a different variable...

6 7
1 4 4 2 5 0 6
1 4 4 0 4 0 2
1 0 4 0 4 6 1
1 2 7 1 0 4 2
3 1 4 2 3 1 5
4 2 5 0 4 5 5

 int c;

            while((c = fgetc(r)) != '\n'){
                variable1 = c - '0';
                variable2 = ???
                }

            fclose(r);
            }

        printf("%i",variable1);
        printf("%i",variable2);

Solution

  • I see you might want to read the following lines with a plenty of numbers next, so here's a common solution that might work for the strings of any length (less than a hundred numbers, that is):

    int idx = 0;
    char var[100];  // change to any number you need
    while((c = fgetc(r)) != '\n') {
        if( c != ' ' ) {
            var[idx++] = c - '0';
        }
    }
    

    In the var you'll have all your numbers. And the idx will point to the character behind the last.