Noxter Noxter - 1 year ago 64
C Question

C - Read text/sentences from file into an array of strings

I am a beginner programmer , studying in an uni. at the moment.
My homework: write a text-based adventere game (after less than 2 months of programming studies :/ ).

The teacher said that the text which the game is using, should be stored in a file.
At the beginning, the program should read in "all the text" from that file, and then, the program should use the text from strings (I guess).

My first thought was that I will read in 1 sentence into 1 string but that just does not want to work out, because the sentences have spaces between the words ofcourse, but when I try to read it in, when the program sees a space, it stores the word in another string instead of the same one.

So, because of this, for example:
I have 4 lines in my txt file:
Line 1: Which way should you go?
Line 2: Forward
Line 3: Left
Line 4: Right

I thought that when I read the text in to 4 strings, then LINE 1 will be in the first string, LINE 2 in the second , etc.
But what happened? 'Which' was in the first string, "way" was in the second string, etc.

Sorry for the bad explanation, but I hope you guys understand what my problem is.
How can I read the Line 1 into the first string ONLY?
I thought the program will not count space as "okay, I should put the word after this space into a new string" ..

This is my code which is causing this "error":

char decisions[4][200];
FILE *fp;
fp=fopen("text.txt", "r");
fscanf(fp, "%s %s %s %s", &decisions[0], &decisions[1], &decisions[2], &decisions[3]);

printf("%s\n %s\n %s\n %s\n", decisions[0], decisions[1], decisions[2], decisions[3]);

decisions[0] should have the question read in from the first line of my txt file, and the other 3 should have the 3 chosing options. Thats what I would like to happen :/

Answer Source

To read line by line, you may use fgets. If you know that MAX bytes of each string is 200 and you have 4 lines, pass it to fgets into this loop:

int i;
for (i=0; i<3; i++)
    fgets(decisions[i], 200, fp);

fgets read n bytes into buffer until found new line or EOF. So, be sure that each line will have no more than 200 chars each.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download