2013-10-13 5 views
-1

다양한 단어/줄 수의 텍스트 파일이 있습니다. 예를 들면 다음과 같습니다.여러 줄의 코드에서 단어 가져 오기 C++

Hi 

My name is Joe 

How are you doing? 

사용자가 입력 한 내용을 가져오고 싶습니다. 그래서 조를 검색하면 알게 될거야. 불행히도, 나는 단지 단어 대신에 각 줄을 출력 할 수있다. 나는 그래서 지금 line[1] = Hi, line[2] = My name is Joe

vector<string> line; 
string search_word; 
int linenumber=1; 
    while (cin >> search_word) 
    { 
     for (int x=0; x < line.size(); x++) 
     { 
      if (line[x] == "\n") 
       linenumber++; 
      for (int s=0; s < line[x].size(); s++) 
      { 
       cout << line[x]; //This is outputting the letter instead of what I want which is the word. Once I have that I can do a comparison operator between search_word and this 
      } 

     } 

라인

이러한 라인의 각 하나를 들고 벡터가 있습니다.

어떻게하면 실제 단어를 얻을 수 있을까요? 다만, 경우 Hi, My, name, is, Joe, How, are, you, doing?,

이 벡터 내에서 특정 키워드를 찾아 가고있다 :

#include <iostream> 
#include <sstream> 
#include <vector> 

int main() { 
    std::istringstream in("Hi\n\nMy name is Joe\n\nHow are you doing?"); 

    std::string word; 
    std::vector<std::string> words; 
    while (in >> word) { 
     words.push_back(word); 
    } 

    for (size_t i = 0; i < words.size(); ++i) 
     std::cout << words[i] << ", "; 
} 

출력 :

+1

'벡터 line;은'vector line;에 대한 오타입니다; – john

+1

무엇이 ??? (추신 :이 의견을 쓰기 전에 귀하의 질문을 2 번 읽었습니다.) – LihO

+0

나는 그 코드를 테스트 한 것으로 의심합니다. 문자열의 형식화 된 입력은 첫 번째 공백까지 읽으며 '\ n'을 볼 수 없습니다. 물론 'int'와 문자열 리터럴을 비교할 수는 없습니다. –

답변

1

operator>> 따라서 이미 말씀으로 입력 단어를 읽고, 구분자로 공백을 사용 이 키워드를 std::string 개체의 형태로 준비하면 다음과 같이 할 수 있습니다.

std::string keyword; 
... 
std::vector<std::string>::iterator i; 
i = std::find(words.begin(), words.end(), keyword); 
if (i != words.end()) { 
    // TODO: keyword found 
} 
else { 
    // TODO: keyword not found 
} 
관련 문제