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