Error while reading C file

Asked

Viewed 549 times

4

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

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

Follow code with error, but I can’t 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);
}

After that I need to add up the figures. Someone?

2 answers

3

You missed the format of the reading of fscanf "%d;%d;d%;%d", the % is after the 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];
}

2


Here is 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 (numeros.txt):

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

Exit:

$ ./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'
  • Oo Thanks. Thanks a lot.

Browser other questions tagged

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