hichamkazan
hichamkazan

Reputation: 333

Read integer line by line in c

I know it's asked before, but I haven't found for what I was searching for.

I have a text document that have:

1 2 3 .
2 3 4 5
3 1 2 .

and i have 4 arrays that I need to put each number on the line in one of them
here's my code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
  FILE *file = fopen("d:\\rf.txt", "r");
  int ch[3];
  int a[3],b[3],c[3];
  int z,x,t,v,i;
  if (file  == NULL) return 1;
  for(i=1;i<=3;i++)
  {
      fscanf(file,"%d %d %d %d",&z,&x,&t,&v);
      ch[i]=z;
      a[i]=x;b[i]=t;c[i]=v;
      printf("%d %d %d %d\n",ch[i],a[i],b[i],c[i]);
  }

  return 0;
}

that's what I get:

1 2 3 0
1 2 3 0
1 2 3 0

Thanks

Upvotes: 1

Views: 1653

Answers (2)

Zach P
Zach P

Reputation: 1791

First - your for loop is not true, I don't think you meant it to be this way. It's supposed to be for(i = 0 ; i < 3 ; i++) as arrays initiallized by a constant SIZE are starting from 0 and going on to SIZE-1 so an array int a[3] would have a[0], a[1], a[2] and not a[1], a[2], a[3]. About the rest of the code...

1 2 3 .
2 3 4 5
3 1 2 .

is the file so what do . supposed to mean ? It's not an integer, it'll be converted to its ASCII value (look it up on google for more information), which is basically a value from 0 to 255 that represents a character - so it actually won't be an error reading, but I don't think that's the result you meant. These are the only problems with these code, I tried it and it worked fine... Just change the for loop.

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726579

Your code reaches the point where there is a dot '.' symbol in the input file, and stops. Since it cannot read it with the %d format specifier, it does not advance the read pointer, so the rest of the input is essentially ignored.

Here is one way of fixing this:

// int z,x,t,v,i; <<== Comment this out
if (file  == NULL) return 1;
for(i=0;i<3;i++) { // <<= Note that indexes go from 0 to 2, not from 1 to 3
    int z;
    if (fscanf(file,"%d",&z) == 1) {
        ch[i]=z;
    } else {
        ch[i]=0;
        fscanf(file,"%*s"); // Ignore the input
    }
    if (fscanf(file,"%d",&z) == 1) {
        a[i]=z;
    } else {
        a[i]=0;
        fscanf(file,"%*s"); // Ignore the input
    }
    if (fscanf(file,"%d",&z) == 1) {
        b[i]=z;
    } else {
        b[i]=0;
        fscanf(file,"%*s"); // Ignore the input
    }
    if (fscanf(file,"%d",&z) == 1) {
        c[i]=z;
    } else {
        c[i]=0;
        fscanf(file,"%*s"); // Ignore the input
    }

    printf("%d %d %d %d\n",ch[i],a[i],b[i],c[i]);
}

Note the use of asterisks with %s format on the lines that read the data to be ignored. The asterisk * tells fscanf to drop the result of the read.

Demo on ideone.

Upvotes: 2

Related Questions