我想知道这是否是将字符串分解为特定变量的安全方式。我目前没有得到正确的结果。需要newFirstName来包含Joe。 newLast名称包含Robbin。 NewTeam包含油工等等。我目前得到的是除了newFirstname之外的所有变量。正确方向的一点将不胜感激。如何用特定分隔符分隔字符串?
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);
看到许多伟大的答案,但我做之前,我想出了:
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());
您不能分配到'.c_str()'这种方式。字符串没有足够的空间分配给您放入它们的字符串。 – Barmar
*我想知道这是否是将字符串分解成特定变量的安全方式* - 快速回答 - 不可以。停止使用强制转换,并停止使用“C”。 – PaulMcKenzie
为什么'std :: string :: c_str()'返回const char *'有一个原因 - 你不能直接修改字符串。 – Barmar