Let's say I have a simple words.txt file that has contents like this:
house
car
horse
So I want to scan those words into an array so it would be words[0] would be house, words[1] would be car etc.. So I am having this problem that it seems I am having an infinite while loop, why is that? And am I scanning the words properly?
#include <stdio.h>
#include <stdlib.h>
#define MAX_WORDS 10
int main() {
FILE *f;
f = fopen("words.txt", "r");
char words[MAX_WORDS];
int i = 0;
while(1) {
fscanf(f, "%s", &words[i]);
if(feof(f)) {
break;
}
i++;
}
fclose(f);
return 0;
}
Your array can hold 1 word or n series of characters. What you want is an array of strings. First dimension must have MAX_WORD size and 2nd MAX_WORD_LEN size.
#include <stdio.h>
#include <stdlib.h>
#define MAX_WORDS 10
#define MAX_LEN 51
int main() {
FILE *f;
f = fopen("words.txt", "r");
char words[MAX_WORDS][MAX_LEN]; /* Can hold MAX_WORDS string of MAX_LEN chars */
int i = 0;
while(1) {
fscanf(f, "%50s", words[i]);
if(feof(f) || i == MAX_WORDS - 1) {
break;
}
i++;
}
fclose(f);
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With