-3

Just got a question regards, when you read lines of text from a text file how would you separate the words and store them into an array.

For example if I have two lines of text in my text file that looks like this:

1005; AndyCool; Andy; Anderson; 23; LA 1006; JohnCool; John; Anderson; 23; LA

How would you split them into based on the ';' . And then store them in 2D array.

Sorry I haven't started my coding just yet to paste it here

Cheers ...

  • Check this out: http://stackoverflow.com/questions/2523467/how-to-split-a-string-to-2-strings-in-c – SatA May 04 '13 at 07:53

3 Answers3

1

Use the strsep function:

char* token;
char* line;

/* I assume the line as loaded from file  */;

if( line != NULL ) {
  while ((token = strsep(&line, ";")) != NULL)
  {
     /* 
         token points to the current extracted string, 
         use it to fill your array 
      */
  }

}
Miguel Prz
  • 13,718
  • 29
  • 42
0

First read using fgets, then use strtok to split a string http://www.cplusplus.com/reference/cstring/strtok/

marcadian
  • 2,608
  • 13
  • 20
0

Look at the manual pages for fopen, fgets, strstr and and strchr and strspn functions ... The strtok and strsep functions also work for most things you will do.

Ahmed Masud
  • 21,655
  • 3
  • 33
  • 58