从文件中逐行读取整数

5

如何在C++中从文件中读取整数到整数数组中?比如,以下文件的内容:

1 2 3 4 5

可以被存储在一个整数数组中。

23
31
41
23

would become:

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

我实际上有两个问题。第一个问题是我不知道该如何逐行读取它们。对于一个整数,这将非常容易,只需使用”file_handler >> number“语法即可。我该如何逐行实现呢?

第二个问题似乎更难以解决 - 我应该如何为这个东西分配内存?:U


使用std::vector代替数组,并通过push_back添加新的整数,向量将自动分配内存以扩展大小。 - piokuc
4个回答

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

嗯,向量...我得通过参数将它传递给另一个函数-这样可以吗?我听说这样做会很慢。 - user2252786
2
如果你传递一个引用,它并不会很慢。而且它可能本来就不会很慢。 - Vaughn Cato
1
@user2252786:它不慢。不要听信你听到的一切(除非是在SO上)。 - Kerrek SB
@user2252786:向量和数组的速度一样快。https://dev59.com/-nA65IYBdhLWcg3wuhIR - Martin York
使用 for(int number; file_handler>>number;) 比使用 while 更加简洁,这是我个人的看法。 - EmilioAK

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

1
你可以使用file >> number来实现。它能够正确处理空格和换行符。
对于可变长度的数组,考虑使用std::vector
这段代码将从文件中读取所有数字,并将其存入一个向量中。
int number;
vector<int> numbers;
while (file >> number)
    numbers.push_back(number);

1

Here's one way to do it:

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

你可以使用std::copy来打印:std::copy(list.begin(), list.end(), std::ostream_iterator<int>(std::cout, "\n")); - Martin York
是的,但我受到分隔符的限制,为了输出的清晰度,我想加上“val:”前缀。 - Peter R

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接