Вопрос

I have to read from a .txt like this (1. - txt line)

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

but I have to read like: "1" first line, attribute to x[0], "2" first line attribute to x[1]. I know how to do that but the problem is that I have to skip to the line 2 and do the same, but it doesn't work. So It'd be like x[2]=1. x[2]=2, x[3]=3, x[4]=1, x[5]=3, x[6]=4 Is there a way for me to do it??? Thanks!


Let me try to be more especific

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

Imagine this is a txt file where 3. 2. and 1. are first, second and third line. I have to read each number on each line and assign to a vet[MAX]; I can do it, but only with the first line. I don't know how to skip to the second one


My code

#include <stdlib.h>

int main (void)
{
char buf[1024];
int numeros[8];

FILE *fp = fopen("teste.txt", "r");
if(fp == NULL)
    return EXIT_FAILURE;

while(fgets(buf, sizeof(buf), fp)) {
    if(buf[0] == '\n')
        continue;

    sscanf(buf, "%d %d %d %d %d %d %d", &numeros[0], &numeros[1], &numeros[2], &numeros[3],&numeros[4], &numeros[5], &numeros[6]);
}

fclose(fp);
    printf(" \n %d \n %d \n %d \n %d \n %d \n %d \n %d", numeros[0], numeros[1], numeros[2], numeros[3],numeros[4], numeros[5], numeros[6]);

}

   the output 

3 4 1 131072 2685712 302692880 4798692 Process returned 53 (0x35) execution time : 0.016 s Press any key to continue.

And I wanted

1 2 2 1 2 3 1 3 4

Это было полезно?

Решение 2

Use the result of sscanf().

You will likely get 2 or 3 each loop. This means 2 or 3 int were successfully scanned. This number can then be used to determine saving the int in numeros[].

int i=0;
while(fgets(buf, sizeof(buf), fp)) {
  int t[7];
  int result = sscanf(buf, "%d %d %d %d %d %d %d", &t[0], &t[1], &t[2], &t[3], &t[4], &t[5], &t[6]);
  if (result <= 0) break;  // EOF, IO error, bad data
  for (int r=0; r<result; r++) {
    if (i >= sizeof(numeros)/sizeof(numeros[0[)) break;  // too many
    numeros[i++] = t[r];
  }
}

Другие советы

Assuming your double use of x[2] is a typo, and assuming the line numbers are not really in the file, all you need is to loop doing:

fscanf(file, "%d", &x[i++]);

until it fails. So remember the check the return value, if it isn't 1 it failed to find a number to convert and store, and you should stop.

Of course, this assumes that x has space enough, and that i is initialized to 0.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top