2013-09-22 2 views
2

텍스트 파일을 읽을 수있는 프로그램을 작성하려고 시도하고 있으며 각 단어를 문자열 유형 벡터의 항목으로 저장하려고합니다. 나는이 일을 매우 잘못하고 있다고 확신하지만, 그렇게 해보려고 노력한 이후로 오랫동안 해왔다. 나는 그것이 어떻게 행해졌는지 잊어 버렸다. 어떤 도움이라도 대단히 감사합니다. 미리 감사드립니다.텍스트 파일에서 벡터 초기화

코드 :

#include <iostream> 
#include <fstream> 
#include <vector> 
#include <string> 

using namespace std; 

int main() 
{ 
    vector<string> input; 
    ifstream readFile; 

    vector<string>::iterator it; 
    it = input.begin(); 

    readFile.open("input.txt"); 

    for (it; ; it++) 
    { 
     char cWord[20]; 
     string word; 

     word = readFile.get(*cWord, 20, '\n'); 

     if (!readFile.eof()) 
     { 
      input.push_back(word); 
     } 
     else 
      break; 
    } 

    cout << "Vector Size is now %d" << input.size(); 

    return 0; 
} 
+2

이 – sehe

+0

전에 종류의 문제를 누락 물어 적이있다 :


그리고 경우에 당신이 선으로 그것을 읽는 것, 당신은 명시 적으로 빈 줄을 처리해야 할 수도 있습니다 이 질문. 현재 코드를 시도 할 때 잘못된 점이 있습니까? 또한 사양의 일부가 누락되었습니다. 모든 단어가 파일에서 별도의 줄에 있어야합니까? – us2012

+0

'word' 변수에 직접 읽을 수있는 동안'cWord' 배열을 사용하여 단어를 저장하는 이유가 있습니까? –

답변

4
#include <fstream> 
#include <vector> 
#include <string> 
#include <iostream> 
#include <algorithm> 
#include <iterator> 

using namespace std; 

int main() 
{ 
    vector<string> input; 
    ifstream readFile("input.txt"); 
    copy(istream_iterator<string>(readFile), {}, back_inserter(input)); 
    cout << "Vector Size is now " << input.size(); 
} 

또는 짧은 : 나는 이미에 StackOverflow에 대해 엄청나게 많은 설명이 있기 때문에 :)

+2

심술 궂은 노인이 되려고 애 쓰지는 않겠지 만, 이미 많은 설명이 있다면, 이것을 올바른 것으로 표시하지 않을 것인가? – us2012

+1

@ us2012 예. 그러나 그것을 작성하는 것이 더 빠릅니다. 엄청나게 많은 복제본은 슬프게도 수천 가지의 나쁜 예를 암시하며, 나는 체질을 느끼지 않았다. 그러나 속임수로 닫으십시오! – sehe

+0

나는 많은 설명이 이미 있다는 것을 깨닫지 못했고 적절한 검색 용어를 찾지 못할 수도 있습니다. 그러나 답변 해 주셔서 감사합니다. –

6

, 설명하지 않을거야

int main() 
{ 
    ifstream readFile("input.txt"); 
    cout << "Vector Size is now " << vector<string>(istream_iterator<string>(readFile), {}).size(); 
} 

여러 가지 가능한 방법 중 하나가 간단합니다.

std::vector<std::string> words; 
std::ifstream file("input.txt"); 

std::string word; 
while (file >> word) { 
    words.push_back(word); 
} 

연산자 >>은 읽는 공백 (줄 바꿈 포함)으로 나눈 단어 만 처리합니다.

std::vector<std::string> lines; 
std::ifstream file("input.txt"); 

std::string line; 
while (std::getline(file, line)) { 
    if (!line.empty()) 
     lines.push_back(line); 
}