Henrique Jesus
Henrique Jesus

Reputation: 85

Save just the second element of each line from a file into a vector in c

I have this function that saves in an integer variable all the numbers from a text file. But I want to make a change so that I can save just the second number in each line into a vector and then print the whole vector. Here is an example of the file.txt:

123  19
321  18
432  9
876  16
875  17

And here is the code that must be changed:

void LerVetor(int *V, int *N)
{
    FILE *fp;
    int marks;
    fp = fopen("dados3.txt", "r");

    if (fp == NULL)
        printf("Falha ao abrir ficheiro\n");

    rewind(fp);

    do
    {
        fscanf(fp, "%d", &marks);
        printf("%d\n", marks);

    } while (!feof(fp));

    fclose(fp);
}

The output is the same as the file.txt because the code just prints the content of the file.

Resume: Save just the second numbers of each line, ex: 19, 18, 9..., in a vector and then print the vector.

Upvotes: 1

Views: 373

Answers (2)

anastaciu
anastaciu

Reputation: 23802

One way you can do it is to pass a pointer to the vector (array of ints) where you need to store the values as a parameter of the function.

To dispose the first value in every line you can use a discard specifier %*d:

Live sample

#include <stdio.h>

void LerVetor(int* vector)
{
    FILE *fp; 

    if (!(fp = fopen("dados3.txt", "r"))){
        perror("Falha ao abrir ficheiro");        //print eventual open file error
        return;
    }

    // keep reading lines discarding first value with %*d avoiding container overflow
    for(int i = 0; fscanf(fp, "%*d %d", &vector[i]) == 1 && i < 100; i++) 
        printf("%d\n", vector[i]);                //printing vector values

    fclose(fp);
}

int main(void)
{
    int vector[100];
    LerVetor(vector);
    return 0;
}

Upvotes: 1

user3629249
user3629249

Reputation: 16540

the following proposed code:

  1. cleanly compiles
  2. groups the variables with where they are used
  3. properly checks and handles I/O errors
  4. read/displays the second number from each line of the file
  5. performs the desired functionality

and now, the proposed code:

#include <stdio.h>
#include <stdlib.h>


void LerVetor( void ) 
{
    FILE *fp = fopen("dados3.txt", "r");
    if( !fp )
    {
        perror("fopen to read: dados3.txt failed");
        exit( EXIT_FAILURE );
    }

    int marks;        
    int dummy;
    while( fscanf(fp, "%d %d", &dummy, &marks) == 2 )
    {
        printf("%d\n", marks);
    }

    fclose(fp);
}

Upvotes: 2

Related Questions