Read integers from a text file with C++ ifstream
The standard line reading idiom:
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
std::ifstream infile("thefile.txt");
std::string line;
while (std::getline(infile, line))
{
std::istringstream iss(line);
int n;
std::vector<int> v;
while (iss >> n)
{
v.push_back(n);
}
// do something useful with v
}
Here's a one-line version using a for
loop. We need an auxiliary construction (credits to @Luc Danton!) that does the opposite of std::move
:
namespace std
{
template <typename T> T & stay(T && t) { return t; }
}
int main()
{
std::vector<std::vector<int>> vv;
for (std::string line;
std::getline(std::cin, line);
vv.push_back(std::vector<int>(std::istream_iterator<int>(std::stay(std::istringstream(line))),
std::istream_iterator<int>())
)
) { }
std::cout << vv << std::endl;
}
First read a line using std::getline
function, then use std::stringstream
to read the integers from the line as:
std::ifstream file("input.txt");
std::vector<std::vector<int>> vv;
std::string line;
while(std::getline(file, line))
{
std::stringstream ss(line);
int i;
std::vector<int> v;
while( ss >> i )
v.push_back(i);
vv.push_back(v);
}
You can also write the loop-body as:
while(std::getline(file, line))
{
std::stringstream ss(line);
std::istream_iterator<int> begin(ss), end;
std::vector<int> v(begin, end);
vv.push_back(v);
}
This looks shorter, and better. Or merge-the last two lines:
while(std::getline(file, line))
{
std::stringstream ss(line);
std::istream_iterator<int> begin(ss), end;
vv.push_back(std::vector<int>(begin, end));
}
Now don't make it shorter, as it would look ugly.