2017-04-13 3 views
-1

이것이 특정 변수로 문자열을 분할하는 안전한 방법인지 궁금합니다. 현재 정확한 결과를 얻지 못하고 있습니다. 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()); 
+1

당신은 .c_str()'이 방법'에 할당 할 수 없습니다. 문자열에는 넣는 문자열에 할당 된 공간이 충분하지 않습니다. – Barmar

+0

* 이것이 특정 변수에 문자열을 분할하는 안전한 방법인지 궁금합니다. * - 빠른 대답 - 아니요. 캐스트 사용을 중지하고 'C'를 사용하지 않습니다. – PaulMcKenzie

+0

'std :: string :: c_str()'이'const char *'를 반환하는 이유가 있습니다. 문자열을 직접 수정할 수 없습니다. – Barmar

답변

1

, 단순한는 stringstreamstd::getline와 함께 사용하는 것입니다, 귀하의 구분 문자를 지정할 수 있습니다.

std::istringstream iss(line); 
std::getline(iss, newFirstName, '|'); 
std::getline(iss, newLastName, '|'); 
std::getline(iss, newTeam, '|'); 
iss >> newAssists; 
iss.ignore(); // drop the '|' 
iss >> newGoals; 

당신이하고있는 방식에는 의견에 표시된 많은 문제가 있습니다. 가장 중요한 오류는 데이터 캡슐화의 가장 중요한 규칙을 깨고 정의되지 않은 동작으로 이어지는 sscanf을 통해 std :: string의 버퍼에 직접 쓰려고했습니다.

1

이것이 특정 변수로 문자열을 분할하는 안전한 방법인지 궁금합니다.

나의 제안 :

  1. 사용 std::istringstreamstd::getline 라인을 토큰 화합니다.
  2. std::stoi을 사용하여 토큰 수를 끌어냅니다.

다음은 작동 예제입니다.

#include <iostream> 
#include <sstream> 
#include <string> 

int main() 
{ 
    std::string line = "Joe|Robbin|Oilers|34|23"; 
    std::istringstream str(line); 

    std::string newFirstName; 
    std::string newLastName; 
    std::string newTeam; 
    std::string newAssistsString; 
    std::string newGoalsString; 

    std::getline(str, newFirstName, '|'); 
    std::getline(str, newLastName, '|'); 
    std::getline(str, newTeam, '|'); 
    std::getline(str, newAssistsString, '|'); 
    std::getline(str, newGoalsString); 

    // Sanity check. 
    if (!str) 
    { 
     std::cout << "Unable to extract the tokens from the line\n"; 
     return EXIT_FAILURE; 
    } 

    int newAssists = std::stoi(newAssistsString); 
    int newGoals = std::stoi(newGoalsString); 

    std::cout 
     << newFirstName << " " 
     << newLastName << " " 
     << newTeam << " " 
     << newAssists << " " 
     << newGoals << std::endl; 

    return EXIT_SUCCESS; 
} 

출력

Joe Robbin Oilers 34 23 
관련 문제