2

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);
lenik
  • 23,228
  • 4
  • 34
  • 43

1 Answers1

0

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.

lenik
  • 23,228
  • 4
  • 34
  • 43
  • These two numbers in the first row represent the number of rows (6) nad columms (7) of the matrix below them as you can see in the picture. What I am trying to do is to store those to values as numberOfRows and numberOfCols. With your code (if I understand it correctly) I will store those two numbers to var[0] and var[1] and after that can reach them. So technically char var[2] will always be enough since I will never be storing more then 2 numbers. – Alexandr Čížek Dec 08 '19 at 17:10
  • @AlexandrČížek yeah, but you can easily reuse `var[100]` when reading the rest of your table =) – lenik Dec 09 '19 at 03:00