2022-04-29

Reading comma-separated words from a file

FILE* inp;
inp = fopen("wordlist.txt","r");        //filename of your data file
char arr[100][5];           //max word length 5
int i = 0;
while(1){
    char r = (char)fgetc(inp);
    int k = 0;
    while(r!=',' && !feof(inp)){    //read till , or EOF
        arr[i][k++] = r;            //store in array
        r = (char)fgetc(inp);
    }
    arr[i][k]=0;        //make last character of string null
    if(feof(inp)){      //check again for EOF
        break;
    }
    i++;
}

I am reading the file words and storing them in the array. My question is: how can I randomly select 7 of these words and store them in the array?

The input file has the following content:

https://ibb.co/LkSJ1SV

meal
cheek
lady
debt
lab
math
basis
beer
bird
thing
mall
exam
user
news
poet
scene
truth
tea
way
tooth
cell
oven


No comments:

Post a Comment