0

I have a file in which each line contains three words that I want to read in an array. The file looks like this:

henry eat apple
mary dance heels
jacob backflip papercup
emma freeze pen
olivia clutch throat
emily faint floor
charlotte hunt mouse
adam cut spera
michael drink beer
liam cry stair
batman jump cape
superman shoot laser
wonderwoman whip criminal
spiderman stick web
green_lantern light ring
hulk smash car
reed pull finger
sue hug shoe
johnny fly fire
thing stare flower 

This is the function I am using to read the lines. I use strtok to put each word in an array.

void ReadArrays(int MenuChoice, char * Number[10][4])
{
    FILE *file;
    int counter=0;
    int NumberCounter=0;
    char line[256];
    file = fopen("numbers.txt","r");
    while (fgets(line, sizeof line, file) != NULL)

     {

         if(counter>=(MenuChoice-1)*10 && counter<=MenuChoice*10-1)
         {


             Number[NumberCounter][0] = strtok(line, " ");
             Number[NumberCounter][1] = strtok(NULL, " ");
             Number[NumberCounter][2] = strtok(NULL, " ");
             Number[NumberCounter][3] = counter;
             NumberCounter++;
         }
         counter++; 
         puts(Number[0][0]);
     }
}
  • MenuChoice is a variable that helps you decide where you want to start reading from. If you choose 1 then you read the first ten lines. If you choose 2, the next 10 lines. That is what that if is about

  • I wanted to put the second condition counter<=MenuChoice*10-1 in the while, but I failed. That way it would not continue reading after you've read the 10 lines you were looking for.

  • Also, I didn't do more checks because I am making this program for myself, so I know the file will always exist or that I won't type "x" instead of a number.

I must be using strtok wrong or something because it simply does not work. The array changes itself. I mean this is the output I get:

henry
mary
jacob
emma
olivia
emily
charlotte
adam
michael
liam
batman jump cape

superman shoot laser

wonderwoman whip criminal

spiderman stick web

green_lantern light ring

hulk smash car

reed pull finger

sue hug shoe

johnny fly fire

thing stare flower
thing stare flower

Normally it should say henry 20 times. I have also checked. It only goes into the IF ten times, so it is impossible for it to change. I have also tried changing the way I was using strtok by using an external string and I wrote something like

strcpy(Number[NumberCount][0],extstring)

and looked for more tokens with extstring while attributing it to Number[NumberCount][1] and Number[NumberCount][2] respectively, but it still didn't work.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Tucker
  • 1

0 Answers0