i was wondering if this was a safe way of splitting up string into specific variables. I am currently not getting the correct results. Need newFirstName to contain Joe. newLast name to contain Robbin. NewTeam to contain Oilers and so on. What i am currently getting is nothing in all of the variables except for newFirstname. A point in the correct direction would be much appreciated.
string line = "Joe|Robbin|Oilers|34|23";
char* strToChar = NULL;
char* strPtr = NULL;
string newFirstName = " ";
string newLastName = " ";
string newTeam = " ";
int newAssists = 0;
int newGoals = 0;
sscanf(line.c_str(), "%[^|]s%[^|]s%[^|]s%d|%d",(char*)newFirstName.c_str(), (char*)newLastName.c_str(), (char*)newTeam.c_str(), &newGoals, &newAssists);
Saw lots of great answers but before i did i came up with:
string line = "Joe|Robbin|Oilers|34|23";
char* strToChar = NULL;
char* strPtr = NULL;
string newFirstName = " ";
string newLastName = " ";
string newTeam = " ";
int newAssists = 0;
int newGoals = 0;
int count = 0;
std::string delimiter = "|";
size_t pos = 0;
std::string token;
while ((pos = line.find(delimiter)) != std::string::npos)
{
count++;
token = line.substr(0, pos);
std::cout << token << std::endl;
line.erase(0, pos + delimiter.length());
switch (count)
{
case 1:
newFirstName = token;
break;
case 2:
newLastName = token;
break;
case 3:
newTeam = token;
break;
case 4:
newGoals = atoi(token.c_str());
break;
}
}
newAssists = atoi(line.c_str());