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);
}

Recommended Answers

All 3 Replies

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);
commented: Exactly what i needed +1

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

#include<iostream>
#include<string>
#include<cstring>
using namespace std;
int main()
{
 char* temp = "NAME: name";
 char* pch;
 pch=strtok(temp," :");
 while(pch!=NULL){
 cout<<pch<<endl;
 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

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.