Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem scanning a string from a text file into an array

Tags:

c

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;
}
like image 977
Aldomond Avatar asked Jun 17 '26 17:06

Aldomond


1 Answers

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;
}
like image 166
alex01011 Avatar answered Jun 20 '26 14:06

alex01011