Read an integer value from a file

Asked

Viewed 190 times

0

I am reading a file with the following lines:

ADD 50
ADD 30
ADD 10
ADD 12

And I wanted to read only the integer values for a vector.

I’m using this code:

while(EOF)
{
        aux=(char*)malloc(1000*sizeof(char));
        if(aux==NULL){
            printf("ERROR, vector\n");
            exit(1);
        }
        aux[i]=fgets(aux,tam);
        i++;
}

However this is not what I want because so I keep the ADD too.

2 answers

1

A very simple solution is to use fscanf and check how many values have been read, and finish when not reading the ones that matter:

int main() {
    int valor;
    FILE *arquivo = fopen("arquivo.txt", "r");

    while(fscanf(arquivo, "%*s %d", &valor) == 1)
    {
        printf("%d\n", valor);
    }

    return 0;
}

The fscanf was used with %*s to read the first string, in this case the ADD and discard its value.

The returned value indicates how many elements you were able to read, which in this case will be 1 if it is still in a valid line. When it reaches the end of the file the read returns 0 that ends the while.

Documentation for the fscanf

0

A possible solution would be to go through the vector and compare when aux[i] = 'A' aux[i+1] = 'D' e aux[i+2] = 'D' you would save the other two values after the blank space that exists between the ADD and the number in another variable and could multiply by 10 and 1. Type A[1]*10 +A[2] ( 5*10 + 0*1 = 50).

Browser other questions tagged

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