2011-02-15 636 views
2

讀取「數字行」並將這些數字存儲在向量中的標準方式是什麼?C++讀取一行數字

file.in 
12 
12 9 8 17 101 2 

我應該一行一行地讀取文件,將行拆分爲多個數字,並將這些標記存儲在數組中嗎?

我該用什麼?

+0

如果你能保證他們會是int的,你可以簡單地閱讀它們,並將它們存儲到一個整數數組(或STL數據結構是怎樣的載體將工作)理所當然地認爲你解釋如何使用解析什麼您正在使用的分隔符。如果輸出可能是其他東西,你可能會想要將東西讀入一個字符串並使用stringstream將它們轉換爲整數。 – RageD 2011-02-15 15:10:07

回答

3
#include <vector> 
#include <fstream> 
#include <iterator> 
#include <algorithm> 

std::vector<int> data; 
std::ifstream file("numbers.txt"); 
std::copy(std::istream_iterator<int>(file), std::istream_iterator<int>(), std::back_inserter(data)); 
2

std :: cin是執行此操作的最標準方法。給std :: cin消除每一個數字之內,所以你做

while(cin << yourinput)yourvector.push_back(yourinput) 

,他們將被自動插入載體:)所有空格

編輯:

如果你想從文件中讀取

,你可以轉換您的std :: CIN因此它會自動讀取一個文件:

freopen("file.in", "r", stdin) 
+0

他希望他們從文本文件中讀取,而不是通過用戶輸入。 – RageD 2011-02-15 15:10:48

+0

你確定`freopen`和`std :: cin`打得不錯嗎? – 2011-02-15 15:16:40

3

這裏是爲O NE的解決方案:

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

int main() 
{ 
    std::ifstream theStream("file.in"); 
    if(! theStream) 
      std::cerr << "file.in\n"; 
    while (true) 
    { 
     std::string line; 
     std::getline(theStream, line); 
     if (line.empty()) 
      break; 
     std::istringstream myStream(line); 
     std::istream_iterator<int> begin(myStream), eof; 
     std::vector<int> numbers(begin, eof); 
     // process line however you need 
     std::copy(numbers.begin(), numbers.end(), 
        std::ostream_iterator<int>(std::cout, " ")); 
     std::cout << '\n'; 
    } 
}