Read an integer value from a file

0

I'm reading a file with the following lines:

ADD 50
ADD 30
ADD 10
ADD 12

And I wanted to read only 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 I keep ADD too.

    
asked by anonymous 10.01.2018 / 00:26

2 answers

1

A very simple solution is to use fscanf and check how many values were read, and end when no read what's interesting:

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 it could read, which in this case will be 1 if it is still on a valid line. When it reaches the end of the file the reading returns 0 which causes while to end.

Documentation for fscanf

    
10.01.2018 / 01:31
0
One possible solution would be for you 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 white space between the ADD and the number in another variable and could multiply by 10 and by 1. Type A[1]*10 +A[2] ( 5*10 + 0*1 = 50).

    
10.01.2018 / 00:38