I have some code i've written and i need to splita string and assign the results to 2 variables type and value

The first part of the string up to the : would the type and what is after the : would be the value

When i output the variables i get NAME as the type variable but the value variable is empty. Is this becuase the temp variable has already been erased? If i take out the type erase, the value erase works but it won't do both

Would it be best to split the string on the :

string temp = "NAME: name";

std::size_t pos;
pos= temp.find(":");
if(pos != string::npos)
	int len = temp.size();
	string type= temp.erase(pos, (len-pos));
	string value = temp.erase(0, pos+2);
8 Years
Discussion Span
Last Post by Ancient Dragon

you want to use the substr() method, not erase(). And delete line 8 because length isn't needed (unless you want to use it somewhere else).

string type = temp.substr(0, pos);
string value = temp.substr(pos+1);

Edited by Ancient Dragon: n/a

Votes + Comments
Exactly what i needed

I don ot think erase() would do the trick.. why not use strtok()?

using namespace std;
int main()
 char* temp = "NAME: name";
 char* pch;
 pch=strtok(temp," :");
 pch=strtok(NULL," :");
 return 0;

Please, If this helped,mark this thread as solved AND add to my reputation points...Thanks!!

"Show me your code and I will tell you who you are.."-Tkud

Edited by tkud: n/a


I don ot think erase() would do the trick.. why not use strtok()?

Bad idea. strtok() will crash the program you posted because it will attempt to change the string literal.

Edited by Ancient Dragon: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.