10 years, 1 month ago.

splitting a string

Hi all,

I have a string which is a collection of information in it separated by commas (CSV) for example:

"[TEST],1,N,2,H"

I have imported '<string>', How would I split the string into a string array?

I looked at sscanf but i get error 304 when I do this:

string data = buff.getNext();
    string prefix = "";
    sscanf (data,"%s,",prefix);

Any Ideas?

Regards, Nick

2 Answers

10 years, 1 month ago.

A couple of things:

1. You need buffer space to store the results of the sscanf. I'm not familiar with "string" as a data type, but declaring prefix as "char prefix[25];" or similar would resolve any segfault due to invalid memory access.

2. Your sscanf is "greedy" and will return the entire string in "data". At least it does in a quick and dirty test on a Mac using gcc. While you could just use a character pointer to move through the string until you find your token - something like this:

char data[] = "[TEST],1,N,2,h";
char *ch;
ch = &data[0];
while ( *ch != 0 && *ch != ',' )
  ch++;
*ch = 0x0;
printf( "first token is <%s>\n", data );

It's probably better to use a standard library like strtok. Here's a link you might find helpful:

http://www.tutorialspoint.com/c_standard_library/c_function_strtok.htm

this is good thanks, if I wanted to get the 1 would i lust change line 3 to [1]?

posted by Nick Oliver 09 Mar 2014

No. That would give you the address of 'T'. Again, strtok is probably better. But, if you know you're looking for the value after the comma, just change line 6 to "ch++;" to move the pointer one more position right - this assumes you're not at the end of the string - and take the contents of that position, "val = *ch;" This would give you '1' in this case.

posted by Aaron Minner 09 Mar 2014
10 years, 1 month ago.

I use the string tokenizer from
http://www.oopweb.com/CPP/Documents/CPPHOWTO/Volume/C++Programming-HOWTO-7.html
and I like very much using the string and vector in a 1768.