5

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

user2252786
  • 1,627
  • 5
  • 21
  • 32
  • Use std::vector instead of the array and push_back new integers, the vector will grow allocating memory automatically – piokuc Apr 20 '13 at 17:15

4 Answers4

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');
}
michael-slx
  • 665
  • 9
  • 15
Vaughn Cato
  • 63,448
  • 5
  • 82
  • 132
2

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.
}
Martin York
  • 257,169
  • 86
  • 333
  • 562
1

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);
yzn-pku
  • 1,082
  • 7
  • 14
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;
}
Peter R
  • 2,865
  • 18
  • 19
  • You can use std::copy to print as well: `std::copy(list.begin(), list.end(), std::ostream_iterator(std::cout, "\n"));` – Martin York Apr 20 '13 at 17:38
  • Yes but I'm limited to a delimiter and for the clarity of the output I wanted to put the "val:" prefix. – Peter R Apr 20 '13 at 18:05