2017-11-30 88 views
-2

나는 쉼표를 없애고 secondWord에 두 번째 단어를 저장하려고 시도한 다음 secondWord을 출력합니다.두 번째 단어를 추출합니다. 문자열 구문 분석 (C++)

내 코드 :

#include <iostream> 
#include <string> 
#include <sstream> 
using namespace std; 

int main() 
{ 
    istringstream inSS;  
    string lineString;   
    string firstWord;   
    string secondWord;  
    int i; 
    bool correct = false; 

    cout << "Enter input string:" << endl; 

    while (!correct) 
    { 
     // Entire line into lineString 
     getline(cin, lineString); 

     // Copies to inSS's string buffer 
     inSS.clear(); 
     inSS.str(lineString); 

     // Now process the line 
     inSS >> firstWord; 

     // Output parsed values 
     if (firstWord == "q") 
     { 
      cout << "q" << endl; 
      correct = true; 
     } 

     inSS >> secondWord; 
     if(secondWord[i] != ',') 
     { 
      cout<<"Error: No comma in string."<<endl; 
     } 

     else if (secondWord[i] == ',') 
     { 

      cout << "First word: " << firstWord << endl; 
      cout << "Second word: " << secondWord << endl; 
      cout << endl; 
     } 
    } 

    return 0; 
} 

허용 입력 : 질, 알렌 질, 알렌 질, 알렌

코드는 두 번째 단어와 쉼표를 생산

expected output

,하지만 난 쉼표와 공백을 없애고 두 번째 단어를 빼내고 싶습니다.

+0

내가 초기화되지 않은 것 같습니다. – lamandy

+0

어쨌든이 질문을 살펴볼 수 있습니다. https://stackoverflow.com/questions/53849/how-do-i-tokenize-a-string-in-c 문자열을 토큰 화합니다. – lamandy

+0

초기화되지 않은 경우 코드 동작이 정의되지 않아 아무 일도 발생할 수 없습니다. 어쨌든, 샘플 입력을 제공해야합니다. 'a, b', a, b','a, b'는 코드를 사용하여 매우 다른 결과를 만들어 낼 수 있습니다. – lamandy

답변

0
vector<string> tokenize(const string& line, const string& delimiters) 
{ 
    int start = 0, end = 0; 
    vector<string> result; 
    while (end != string::npos) 
    { 
     start = line.find_first_not_of(delimiters, end); 
     end = line.find_first_of(delimiters, start); 
     if (start != string::npos && end != string::npos) 
      result.push_back(line.substr(start, end - start)); 
     else if (start != string::npos) 
      result.push_back(line.substr(start)); 
     else 
      break; 
    } 
    return result; 
} 

이 메서드는 구분 기호로 구분 된 토큰을 반환합니다. 구분 기호가 ", " 인 경우 사이에 쉼표가 있는지 확인해야합니다. 구분 기호가 "," 인 경우 각 단어의 처음과 끝에 공백을 자르고 싶을 것입니다.