이것이 특정 변수로 문자열을 분할하는 안전한 방법인지 궁금합니다. 현재 정확한 결과를 얻지 못하고 있습니다. Joe를 포함하려면 newFirstName이 필요합니다. newLabbin은 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