1

I'm currently trying to read in a file delimited by spaces. I have been able to get it to read line by line, but now I need to separate it by spaces so that I can put it into an array. How does one separate it into the array?

#include <stdio.h>
int main ( void )
{
    int data_array[3];
    int num1;
    int num2;
    int num3;

    static const char data[] = "data.txt";
    FILE *file = fopen ( data, "r" );
    if ( file == NULL )
    {
        printf("An error occured reading the file. Check to make sure file is not locked.");
    }
    else
    {
        char line [ 1024 ]; // hopefully each line does not exceed 1024 chars
        while ( fgets ( line, sizeof line, file ) != NULL ) // reads each line
        {
            // reads each number into an array
            scanf("%d %d %d", num1, num2, num3);
            data_array[0] = num1;
            data_array[1] = num2;
            data_array[2] = num3;
        }
        fclose ( file ); // closes file
    }
    return 0;
}
Zombo
  • 1
  • 62
  • 391
  • 407
RS Evolve
  • 13
  • 4
  • 1
    Sorry, but i didn't understand what you want to do. Do you want to store the data_array's inside another array? – Lucas Piske Sep 08 '15 at 01:40
  • My file has a line like so: `3 5 12` And I want to read each of these numbers into the array data_array. – RS Evolve Sep 08 '15 at 01:40
  • I guess you forgot to paste the line. – Lucas Piske Sep 08 '15 at 01:42
  • You forgot to add the & before the variables being passed to the scanf. Like: scanf("%d %d %d", &num1, &num2, &num3); – Lucas Piske Sep 08 '15 at 01:44
  • Depending on what you want to do, you could either replace the `fgets` call with calls to `fscanf` calls operating directly on the `file`, or if you need to keep the `line`s as well, you could use `sscanf` to extract the numbers from the `line`. – FriendFX Sep 08 '15 at 01:45
  • What solutions have you tried so far? Did you search in SO? Did you check this https://stackoverflow.com/questions/13394102/reading-formatted-file-into-char-array-in-c?rq=1 ? – MASL Sep 08 '15 at 01:59

1 Answers1

0
scanf("%d %d %d", num1, num2, num3);

Since you already read characters from file to line, you should change this into sscanf() like

sscanf(line, "%d %d %d", &num1, &num2, &num3);
timrau
  • 22,578
  • 4
  • 51
  • 64