2009-11-04 43 views
4

如何讀取文件中的每行是單個數字,然後將該數字輸出到行向量中?將std :: ifstream讀入行向量

例如:file.txt的包含:

314 
159 
265 
123 
456 

我已經試過這樣實現:

vector<int> ifstream_lines(ifstream& fs) { 
    vector<int> out; 
    int temp; 
    getline(fs,temp); 
    while (!fs.eof()) { 
     out.push_back(temp); 
     getline(fs,temp); 
    } 
    fs.seekg(0,ios::beg); 
    fs.clear(); 
    return out; 
} 

但是當我嘗試編譯,我得到的錯誤,如:

error C2784: 'std::basic_istream<_Elem,_Traits> &std::getline 
(std::basic_istream<_Elem,_Traits> &,std::basic_string<_Elem,_Traits,_Alloc> &)' : 
could not deduce template argument for 'std::basic_istream<_Elem,_Traits> &' from 'std::ifstream' 

所以,顯然有些事情是錯誤的。有沒有比我想要的更優雅的解決方案? (假設像Boost這樣的第三方庫不可用)

謝謝!

回答

20

我懷疑你想是這樣的:

#include <vector> 
#include <fstream> 
#include <iterator> 

std::vector<int> out; 

std::ifstream fs("file.txt"); 

std::copy(
    std::istream_iterator<int>(fs), 
    std::istream_iterator<int>(), 
    std::back_inserter(out)); 
+0

完美!謝謝! – 2009-11-04 17:58:15

+1

您應該注意,它不會檢測輸入文件中的錯誤(即同一行中有兩個數字)。 – 2009-11-04 18:57:43

+0

流迭代器將從單行讀取多個值,以空格分隔,但如果遇到除數字或空格以外的內容,它將停止,並使用'fs.eof()== false'和'fs。失敗()== true'。 – 2009-11-04 19:28:18

1

std::getline(stream, var)讀入一個std ::字符串變種。我建議使用流運營商如果需要讀入int,而不是,並檢查錯誤:

vector<int> ifstream_lines(ifstream& fs) { 
    vector<int> out; 
    int temp; 
    while (!(fs >> temp).fail()) { 
    out.push_back(temp); 
    } 
    fs.seekg(0,ios::beg); 
    fs.clear(); 
    return out; 
} 
+0

太可怕了。切勿測試條件中的eof()。這是__ALWAYS__更好地測試條件下的行動。 – 2009-11-04 18:09:06

5

標準的迭代器由「添西爾維斯特」形容是最好的答案。

但是,如果你想有一個手動循環,然後,
只需提供一個反例也:「jamuraa」

vector<int> ifstream_lines(ifstream& fs) 
{ 
    vector<int> out; 
    int temp; 

    while(fs >> temp) 
    { 
     // Loop only entered if the fs >> temp succeeded. 
     // That means when you hit eof the loop is not entered. 
     // 
     // Why this works: 
     // The result of the >> is an 'ifstream'. When an 'ifstream' 
     // is used in a boolean context it is converted into a type 
     // that is usable in a bool context by calling good() and returning 
     // somthing that is equivalent to true if it works or somthing that 
     // is equivalent to false if it fails. 
     // 
     out.push_back(temp); 
    } 
    return out; 
}