user2252786
user2252786

Reputation: 1635

Read integers from file - line by line

How can I read integers from a file to the array of integers in c++? So that, for example, this file's content:

23
31
41
23

would become:

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

?

I actually have two problems with this. First is that I don't really know how can I read them line by line. For one integer it would be pretty easy, just file_handler >> number syntax would do the thing. How can I do this line by line?

The second problem which seems more difficult to overcome for me is - how should I allocate the memory for this thing? :U

Upvotes: 5

Views: 7660

Answers (4)

Vaughn Cato
Vaughn Cato

Reputation: 64308

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

Upvotes: 3

Loki Astari
Loki Astari

Reputation: 264331

don't use array use vector.

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

Upvotes: 2

Peter R
Peter R

Reputation: 2985

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

Upvotes: 1

yzn-pku
yzn-pku

Reputation: 1082

You can just use file >> number for this. It just knows what to do with spaces and linebreaks.

For variable-length array, consider using std::vector.

This code will populate a vector with all numbers from a file.

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

Upvotes: 1

Related Questions