Read txt file names in C

Asked

Viewed 53 times

1

So basically the code needs to read the names of a txt file (AFTER I WILL MANIPULATE THEM) until it has the word 'end. In that part of the code where it reads the lines, it just stores the 1 string of the line and ignores the ones that come after and then it jumps the line to the next name. I need help reading the whole line and storing the names.

This part here that’s the problem, it separates the line into strings, but it’s just taking a string

aux = strtok(frase," ");

The file has these names:

Arya Meryn 
Meryn Syrio 
Brienne Stannis 
Ellaria Myrcella 
Jaime Aerys 
Brienne Jaime 
FIM

Code does not read 2 line names

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

int main(){

    int contador;
    char *aux;
    char frase[1000];
    char *vetor[250];
    char vetor2[200][200];

    FILE *arquivo;
    arquivo = fopen("nomes.txt","r");
    contador = 0;
    do{
        fgets(frase,100,arquivo);
        strlwr(frase);

        aux = strtok(frase," ");
        vetor[contador] = aux;
        strcpy(vetor2[contador],vetor[contador]);

        printf("-->%s\n",vetor[contador]);
        contador ++;

    }while(strcmp(frase,"fim")!=0);
    contador --;
    for(int i =0;i<contador;i++){
        printf(" %s \n",vetor2[i]);
    }
}

1 answer

1

The problem lies in your interpretation of strtok. What the function does is to navigate token to token ("word" to "word") over what has been passed. Each navigation is done to each call from strtok. It means you’re gonna split it into three words and you want to get all three, you have to have three calls to strtok. So this is typically using with a while.

Watch out for this piece of documentation:

On a first call, the Function expects a C string as argument for str, Whose first Character is used as the Starting Location to scan for tokens. In subsequent calls, the Function expects a null Pointer and uses the position right after the end of the last token as the new Starting Location for Scanning.

Translating:

In the first call the function experiences a C-style string as argument for str where the first character is used as the start of the path to go through to get tokens. In the following calls, the function waits for a null pointer and uses the position after the last token found as the starting position to find the next.

In your code if we assume that there are 2 names separated by a space on each line, with a space at the end as in your example, just do the following:

char *nome1, * nome2;
...
do{
    fgets(frase,100,arquivo);
    strlwr(frase);

    nome1 = strtok(frase," "); //le o primeiro nome
    nome2 = strtok(NULL, " "); //le o segundo utilizando NULL na chamada ao strtok
    printf("%s, %s\n", nome1, nome2);

}while(strcmp(frase,"fim")!=0);

Browser other questions tagged

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