Reading integers from a file - line by line

How can I read integers from a file into an array of integers in C ++? So, for example, this is the contents of the file:

23 31 41 23 

will become:

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

?

I actually have two problems. Firstly, I do not know how I can read them line by line. For one, it would be pretty easy, just the syntax file_handler >> number could do it. How to do this line by line?

The second problem, which seems harder to overcome, is how do I allocate memory for this thing ?: U

+4
source share
4 answers
 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'); } 
+3
source

do not use an 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. } 
+2
source

Here is one way to do this:

 #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; } 
+1
source

You can simply use file >> number to do this. He just knows what to do with spaces and lines.

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

This code fills the vector with all the numbers from the file.

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

All Articles