2012-09-24 3 views
0

텍스트 파일을 구문 분석하고 처리하기위한 프로그램을 작성하려고합니다. sscanf을 구현하지 못한 후 문자열 스트림을 사용하기로 결정했습니다.stringstream이 예상대로 작동하지 않습니다.

Counter: 4 
Variable number 1 : VARIABLE_STRING_NO_1 
Variable number 2 : VARIABLE_STRING_NO_2 
Variable number 3 : VARIABLE_STRING_NO_3 
Variable number 4 : VARIABLE_STRING_NO_4 
: some_string VARIABLE_STRING_NO_1 을 yet_another_string another_string

I 코드를 작성하고 예상되는 결과가 될 것이다

을 next_string :

I과 같은 공간에 의해 분리 된 데이터를 포함하는 문자열 벡터 가지고

대신 다음과 같이 표시됩니다.

Counter: 4 
Variable number 1 : VARIABLE_STRING_NO_1 
Variable number 2 : VARIABLE_STRING_NO_1 
Variable number 3 : VARIABLE_STRING_NO_1 
Variable number 4 : VARIABLE_STRING_NO_1 

누구나 나를 올바른 방향으로 밀고 갈 수 있습니까? (벡터 대신 다른 컨테이너를 사용하는 등 ...)

VARIABLE_STRING에는 공백이있는 2 개의 하위 문자열이 포함되어 있습니까? 그것은 내 데이터에서 가능합니다.

샘플 코드 :

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

int main() 
{ 
    vector<string> vectorOfLines, vectorOfData; 

    vectorOfLines.push_back("some_string another_string yet_another_string VARIABLE_STRING_NO_1 next_string"); 
    vectorOfLines.push_back("some_string another_string yet_another_string VARIABLE_STRING_NO_2 next_string"); 
    vectorOfLines.push_back("some_string another_string yet_another_string VARIABLE_STRING_NO_3 next_string"); 
    vectorOfLines.push_back("some_string another_string yet_another_string VARIABLE_STRING_NO_4 next_string"); 

    string data = "", trash = ""; 
    stringstream token; 

    int counter = 0; 

    for(int i = 0; i < (int)vectorOfLines.size(); i++) 
    { 
     token << vectorOfLines.at(i); 
     token >> trash >> trash >> trash >> data >> trash; 
     vectorOfData.push_back(data);      // wrong method here? 
     counter++;           // counter to test if for iterates expected times 
    } 

    cout << "Counter: " << counter << endl; 

    for(int i = 0; i < (int)vectorOfData.size(); i++) 
    { 
     cout << "Variable number " << i + 1 << " : " << vectorOfData.at(i) << endl; 
    } 

    return 0; 
} 

변명 내 초보자 질문하지만 최근 5 일 동안 다른 접근을 시도한 후, 나는 욕설과 학습을 계속하는 스타일을 장려을 얻기의 지점에 도착.
예 저는 C++을 처음 접했습니다.
나는 PHP에서 똑같은 프로그램을 성공적으로 마쳤습니다. (이것 역시 총 초보자입니다.) C++은 훨씬 더 어렵습니다.

+0

'token >> trash >> trash >> trash >> data >> trash;의 목표는 무엇입니까? – BostonJohn

+0

그건 그렇고,'tokenO'에 삽입하기 전에'vectorOfLines.at (i)'를 출력하면 정확한 결과가 나오고, 줄을 삽입 한 직후에'token.str()'을 출력하면 항상 첫 번째 줄이됩니다. – chris

+2

>> 연산자가 성공했는지 확인해야합니다. 그렇지 않으면 이전 반복에서 문자열의 이전 값을 사용하고 있습니다. – Flexo

답변

4

개인을 읽은 후 문자열 스트림을 재설정하려고합니다. 이 모양에서 사용중인 문자열 스트림은 실패 상태가됩니다. 이 시점에서 상태가 clear()이 될 때까지 더 이상의 입력을 제외하지 않습니다. 또한 항상을 읽음으로써 성공적으로 읽었는지 확인해야합니다.

token.clear(); 
token.str(vectorOfLines[i]); 
if (token >> trash >> trash >> trash >> data >> trash) { 
    process(data); 
} 
else { 
    std::cerr << "failed to read '" << vectorOfLines[i] << "\n"; 
} 

나는 또한 단지 std::istringstream을 사용 : 그건 내가 같은 루프 뭔가의 몸을 시작할 것입니다.

+0

덕분에 이제는 C++로 다시 재생할 수 있습니다. 이 유용한 커뮤니티를 사랑하십시오! – RegEx

관련 문제