You have to keep in mind that a string vector on C is actually a matrix of char
, See the example below:
char* palavras[50];
Above I declared a vector with a pointer pointing to the word. This vector has the capacity to store 50 words, and the number of characters of the words can be any one, because it will depend on the size of the word that will be in the file palavras.txt
.
I assumed that the content structure of the text file palavras.txt
is as follows:
computador
gato
mundo
cachorro
casa
stack
over
flow
Here follows an example of a program that reads the words of the text file and stores in the vector palavras
the words read:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int i = 0;
int numPalavras = 0;
char* palavras[50];
char line[50];
FILE *arquivo;
arquivo = fopen("palavras.txt", "r");
if (arquivo == NULL)
return EXIT_FAILURE;
while(fgets(line, sizeof line, arquivo) != NULL)
{
//Adiciona cada palavra no vetor
palavras[i] = strdup(line);
i++;
//Conta a quantidade de palavras
numPalavras++;
}
int j;
for (j = 0; j < numPalavras; j++)
printf("\n%s", palavras[j]); //Exibi as palavras que estao no vetor.
printf("\n\n");
fclose(arquivo);
return EXIT_SUCCESS;
}
Exit from the program:
computador
gato
mundo
cachorro
casa
stack
over
flow
Notice that I had to use the function strdup
to return the string pointer that is stored in line
which in this case is the word, without it all the pointers of the words would point to the same location, if I’m not mistaken it would point to the last word of the file flow
, to check just do the test by replacing the line palavras[i] = strdup(line);
for palavras[i] = line;
to see the result.
To learn more about the function strdup
see this question.
Sources:
Reading Lines from c file and putting the strings into an array.
How do I create an array of strings in C?
Have you started? What have you done so far?
– Ari
I read the first word down to the first space, but then I don’t know how to continue reading and storing.
– S Flavio
Post the code.
– rubStackOverflow