2013-09-22 18 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

是否有理由使用數組'cWord'來存儲單詞,而您可以直接讀入'word'變量? –

回答

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(); 
} 

或者更短:

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

我不打算去解釋,因爲在計算器上有,卻有無數的解釋已經:)

+2

不要試圖成爲一個脾氣暴躁的老傢伙,但是如果已經有了數十億的解釋,那麼正確的做法是否將這個標記爲重複? – us2012

+1

@ us2012是的。但是寫出來會更快。一個萬億的複製品令人遺憾地暗示着五十萬個不好的例子,我不想篩選。但是,請隨時關閉! – sehe

+0

我沒有意識到已經有很多解釋,我可能無法拿出適當的搜索條件。謝謝你,但是回答。 –

6

其中一種方法很簡單:

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); 
}