Noxter Noxter - 1 month ago 5
C Question

C - Read from file, but not every line

** IMPORTANT ** : I am a beginner in programming , so I only know some "basic" codes and methods to do stuff, so when writing an answer, keep in mind, that I might need a little bit of more explanation than usually people need on this site. Thank you!! **

I have a homework of doing a text-based adventure game.
I MUST read the text from a file into the program to use.

At first I thought that I will write The 'Question' in one line,
And the next 3 lines after that line will be the lines having the 3 "choosing options".

With this method, I would have to create 4 array of strings (questions, ans1, ans2 and ans3) and then read every 4th line into every one of these strings (starting from a different line ofc.).

I hope you guys understand what I would like to do here. The question is, though, that, is that possible?
If yes, then how?

Currently I have this code, but this would read every line into the string if I put it in a cycle (for/while/etc.), but that is not good, cause I only need every 4th line into one array of strings.
Is that possible, to tell the program, to only read in every 4th line from the file??

My current code is:

char questions[40][200];
FILE* fp;
fp=fopen("text.txt", "r");
int i;
for (i=0; i<=3; i++)
{
fgets(questions[i], 200, fp);
}
fclose(fp);


This would get the first 4 lines into the string which is not good. I would like the first 4 questions in my string in this case. How should I change my code to accomplish that?

Thank you guys and sorry for the amateur question!

Answer

One way to do it is to read all of the lines in your loop. Create additional arrays for each of your question options (e.g. an array to hold all "A" answers), then read them all in an interlaced format:

char questions[40][200];
char answersA[40][200];
char answersB[40][200];
char answersC[40][200];
/* ... */
for (i=0; i<=3 /* Or however many questions there are */; i++)
{
    fgets(questions[i], 200, fp); /* Read the question */
    /* Read the answers */
    fgets(answersA[i], 200, fp); /* Read the answer for option A */
    fgets(answersB[i], 200, fp); /* Read the answer for option B */
    fgets(answersC[i], 200, fp); /* Read the answer for option C */
}
/* ... */

Addition

Then, if you want to get the three answer options for a particular question i, just get answersA[i], answersB[i], and answersC[i].