2013-04-20 182 views
4

如何從文件讀取整數到C++中的整數數組?因此,例如,該文件的內容:從文件中逐行讀取整數

23 
31 
41 
23 

將成爲:

int *arr = {23, 31, 41, 23}; 

我其實有兩個問題。首先,我不知道我該如何逐行讀取它們。對於一個整數來說,這將非常容易,只要file_handler >> number語法就可以做到這一點。我如何一行一行地做這件事?

第二個問題似乎更難以克服的是我應該如何爲這個東西分配內存? :U

+0

使用std ::矢量而非陣列和新的push_back整數,向量將增長分配內存自動 – piokuc 2013-04-20 17:15:52

回答

3
std::ifstream file_handler(file_name); 

// use a std::vector to store your items. It handles memory allocation automatically. 
std::vector<int> arr; 
int number; 

while (file_handler>>number) { 
    arr.push_back(number); 

    // ignore anything else on the line 
    file_handler.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 
} 
+0

呃,載體......我不得不通過參數來傳遞這一個到另一個功能 - 是這好嗎?我聽說它很慢。 – user2252786 2013-04-20 17:17:10

+2

@ user2252786:如果你傳遞一個引用,它不會很慢。反正它可能並不那麼慢。 – 2013-04-20 17:17:42

+1

@ user2252786:這並不慢。不要聽你所聽到的一切(除了它在這裏)。 – 2013-04-20 17:24:41

0

您只需使用file >> number即可。它只知道如何處理空格和換行符。

對於可變長度陣列,請考慮使用std::vector

此代碼將使用文件中的所有數字填充矢量。

int number; 
vector<int> numbers; 
while (file >> number) 
    numbers.push_back(number); 
1

下面是做這件事:

#include <fstream> 
#include <iostream> 
#include <iterator> 

int main() 
{ 
    std::ifstream file("c:\\temp\\testinput.txt"); 
    std::vector<int> list; 

    std::istream_iterator<int> eos, it(file); 

    std::copy(it, eos, std::back_inserter(list)); 

    std::for_each(std::begin(list), std::end(list), [](int i) 
    { 
     std::cout << "val: " << i << "\n"; 
    }); 
    system("PAUSE"); 
    return 0; 
} 
+0

你也可以使用std :: copy來打印:'std :: copy(list.begin(),list.end(),std :: ostream_iterator (std :: cout,「\ n」));' – 2013-04-20 17:38:12

+0

是的,但我只限於分隔符,爲了輸出的清晰度,我想放置「val:」前綴。 – 2013-04-20 18:05:20

2

不使用陣列中使用向量。

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

int main() 
{ 
    std::ifstream  file("FileName"); 
    std::vector<int> arr(std::istream_iterator<int>(file), 
          (std::istream_iterator<int>())); 
         // ^^^ Note extra paren needed here. 
}