簡體   English   中英

從文件中讀取整數-逐行讀取

[英]Read integers from file - line by line

如何在C ++中從文件讀取整數到整數數組? 這樣,例如,該文件的內容:

23
31
41
23

會成為:

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

我實際上有兩個問題。 首先是我真的不知道如何逐行閱讀它們。 對於一個整數,這將非常容易,只需使用file_handler >> number語法即可。 如何逐行執行此操作?

對我來說,似乎更難克服的第二個問題是-我應該如何為這件事分配內存? :U

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

不要使用數組使用向量。

#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.
}

這是一種實現方法:

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

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

對於可變長度數組,請考慮使用std::vector

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM