Parsing Strings

14 Jan 2010 . Edited: 14 Jan 2010

Hi,

I would like to be able to get 5 integers from a line in a text file on the local file system. They are comma seperated and there will always be 5 integers per line.

Is there a function within the mbed librarys to help accomplish this as it would appear there is nothing like the vb split() available in c?

Thanks.

Michael.

14 Jan 2010

You should maybe look at strtok() if its a character array, though many don't like them, preferring strings, in which case, look at tokenizing here

 

Dave

14 Jan 2010

Congrats, you've got topic number 404!

That said, something like this should work:

int i1, i2, i3, i4, i5;
FILE* f = fopen("/local/file.txt","r");
if ( f == NULL)
  error("Could not open file");

int line = 0;
while (!feof(f))
{
  line++;
  if ( 5 != fscanf(f, "%d,%d,%d,%d,%d\n", &i1, &i2, &i3, &i4, &i5) )
  {
    printf("Error in line %d!\n", line);
    continue;
  }
  printf("Line %d, sum: %d\n", line, i1+i2+i3+i4+i5);
}
fclose(f);

You might have to replace \n in the scanf call by \r\n, if your file comes from Windows.

14 Jan 2010

Thanks Igor, Perfect!

 

Mike.