Reading values from a C file

Asked

Viewed 63 times

0

I have a file containing the following values:

10 20 30
40 50 60

For each line, the values must be stored in a vector.

How do I get such values from the file, knowing that there is no exact amount for each line ?

  • You’ve already tried to do something?

  • @Cesarmiguel , already tried everything: fgets, fgetc, fscanf...

  • Whereas there is at least one integer in each row, read an int and char. If the char is n or EOF, the line/file is finished.

1 answer

1

I’ll assume that Voce can read every line in your file, okay?

This code here takes every number of a line:

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

int main() {
    char linha[] = "10 100 1000";
    char *num;
    int x;
    num = strtok(linha, " \n\r");
    while (num != NULL) {
        sscanf(num, "%d", &x);
        printf("%d\n", x);
        num = strtok(NULL, " \n\r");
    }
    return 0;
}

What he does and tokenizar the line, that is, it extracts the elements from the string linha. These elements are the 'things' between spaces or the end of the line, so the numbers.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.