Reputation: 171
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;
}
Upvotes: 3
Views: 219
Reputation: 1702
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;
}
Upvotes: 2
Reputation: 1856
First, you should think about the array storing the strings. Remember that strings are arrays by them selves. When you know the maximal length of the words it is easy to define this array of char arrays:
#define MAX_WORD_LEN 32
char words[MAX_WORDS][MAX_WORD_LEN];
Then you can read each string like this
fscanf(f, "%s", words[i]);
Note: your code can lead to buffer overflows, because you do not have a check for the variable i
and "%s"
is considered insecure (like gets
), because it assumes that the read string fits into the buffer. Do not use these if possible, otherwise use these only, when you trust the input: Never: or scanf("%s", ...);
gets(...)
If you know the width, you can use it with scanf as the following:
char str[11];
scanf("%10s", str); // one less than the buffer size
Upvotes: 2