Read integers from a text file with C++ ifstream
c++
Solution
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;
}
Problem
I want to read graph adjacency information from a text file and store it into a vector. the file has arbitrary number of lines each line has arbitrary number of integers ended with '\n' for example, ``` First line: 0 1 4 Second line: 1 0 4 3 2 Thrid line: 2 1 3 Fourth line: 3 1 2 4 Fifth line: 4 0 1 3 ``` If I use getline() to read one line at a time, how do I parse the line (as each line has variable number of integers)? Any suggestions?