Error reading file in C

4

But before doing this code I created a text file called numero.txt and included in the file:

23;45;89;-230
452;0;97;1
87;2;4;6
346;97;-5;3

Following is an error code, but I can not find the error.

#include<stdio.h>

void main(){
    FILE *arq;
    int num[4]; 
    int i;

    arq =fopen("numero.txt", "r");

    while(!feof(arq)){
        fscanf(arq, "%d;%d;d%;%d",&num[0], &num[1], &num[2], &num[3] );

    for(i = 0; i<4; i++){
        printf("[%d]=%d\t", i, num[i]);         
    }
    printf("\n");
 }
 fclose(arq);
}

Then I need to add the values. Someone?

    
asked by anonymous 01.06.2016 / 19:43

2 answers

2

Here's a solution to your problem:

#include <stdio.h>

int main( int argc, char * argv[] )
{
    FILE * pf = NULL;
    int n[4];
    int i = 0;
    int linha = 0;
    int ret = 0;
    int soma = 0;

    pf = fopen( argv[1], "r" );

    if(!pf)
    {
        printf("Erro abrindo arquivo para leitura: %s\n", argv[1] );
        return 1;
    }

    while(1)
    {
        linha++;

        ret = fscanf( pf, "%d;%d;%d;%d", &n[0], &n[1], &n[2], &n[3] );

        if( ret != 4 )
        {
            printf("Registro contido na linha %d estah malformado.\n", linha );
            break;
        }

        printf( "Linha %d => ", linha );

        for( i = 0; i < 4; i++ )
            printf("n[%d] = '%d'\t", i, n[i] );

        for( i = 0, soma = 0; i < 4; i++ )
            soma += n[i];

        printf( "soma = '%d'\n", soma );
    }

    fclose(pf);

    return 0;
}

/* fim-de-arquivo */

Input File (numbers.txt):

23;45;89;-230
452;0;97;1
87;2;4;6
346;97;-5;3
123;890;-1;-2

Output:

$ ./foobar numeros.txt
Linha 1 => n[0] = '23'  n[1] = '45' n[2] = '89' n[3] = '-230'   soma = '-73'
Linha 2 => n[0] = '452' n[1] = '0'  n[2] = '97' n[3] = '1'  soma = '550'
Linha 3 => n[0] = '87'  n[1] = '2'  n[2] = '4'  n[3] = '6'  soma = '99'
Linha 4 => n[0] = '346' n[1] = '97' n[2] = '-5' n[3] = '3'  soma = '441'
Linha 5 => n[0] = '123' n[1] = '890'    n[2] = '-1' n[3] = '-2' soma = '1010'
    
01.06.2016 / 20:38
3

You missed the reading format for fscanf "%d;%d;d%;%d" , % is after d .

The sum if adding the values of the file in a single variable would be

for(i = 0; i<4; i++){
    printf("[%d]=%d\t", i, num[i]);
    sum+= num[i];
}

If it is in a sum vector, it should not be.

for(i = 0; i<4; i++){
    printf("[%d]=%d\t", i, num[i]);
    sum[i] += num[i];
}
    
01.06.2016 / 20:25