Click to See Complete Forum and Search --> : How to parse comma delimited string?
ChuckB
Sep 26th, 2002, 10:03 PM
Hi,
I can read a comma delimited file and load the data into a string one line at a time. So, I can get something like...
string s;
s = "12.3, 14.5, 16.7";
I can iterate through the string using s.substr and a 'for' loop...is there an equivalent to 'instr' command as in basic?
Regards,
ChuckB
Zaei
Sep 26th, 2002, 10:06 PM
std::string::find().
Z.
Zaei
Sep 26th, 2002, 10:06 PM
Though I believe that the boost library (http://www.boost.org/ ) has a handy string_tokenizer class that will do that work for you =).
Z.
ChuckB
Sep 27th, 2002, 09:33 AM
Z,
Thanks for the link. They have a lot of samples using iterators...which is what I needed to see. Are you holding out on some other real usefull C++ sites? :-)
Regards,
ChuckB
jim mcnamara
Sep 27th, 2002, 10:08 AM
Don't overlook strtok() for char * -
#include <stdio.h>
#include <string.h>
int main(){
char *whatever=
"this is an, example, showing parsing using, commas and spaces.";
char *p;
p=strtok(whatever,", "); /* find the first space */
while(p){
printf("%s\n",p);
p=strtok('\0'," ,"); /* use spaces & commas*/
}
return 0;
}
parksie
Sep 27th, 2002, 11:57 AM
Just be bloody careful with where you point strtok -- it changes the string you pass in.
Also, I don't think you can use strtok simultaneously on multiple strings.
CornedBee
Sep 27th, 2002, 04:39 PM
strtok doesn't change the string, but you can't use it on more than one string, that's right. And it is not thread-safe.
jim mcnamara
Sep 27th, 2002, 04:50 PM
strtok behaves differently on different boxes. Parksie is right - on HP UX 11.0, for example, it does change the source string.
strtok_r uses a third argument - a char* - that stops strtok from clobbering the source.
In MSVC++ it does not hurt the source.
parksie
Sep 27th, 2002, 04:57 PM
Quick aside for anyone else... the "_r" means "reentrant", which basically says that it's possible to call the function twice in the same process, at the same time (such as multiple threads). Reentrant functions don't have any static data, or anything like that.
Well, they could. But they don't cause massive lossage if you do it ;)
CornedBee
Sep 27th, 2002, 05:27 PM
Another side note: the strtok of MSVC++ in the dynamic or multithreaded static CRT library is thread-safe.
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.