Read Integers from a Text File with C ifstream
Retrieving and storing graph adjacency information from a text file into a vector presents a challenge when dealing with lines of variable integer count. Here's a comprehensive solution using C 's ifstream:
The traditional approach involves reading each line using getline() and employing an input string stream to parse the line. This technique works well for lines with a consistent number of integers.
#include
#include
#include
std::ifstream infile("text_file.txt");
std::string line;
while (std::getline(infile, line)) {
std::istringstream iss(line);
int n;
std::vector v;
while (iss >> n) {
v.push_back(n);
}
// Process the vector v
}
However, if you have lines with varying integer counts, there is a one-line solution that leverages a loop and the 'stay' idiom, courtesy of Luc Danton:
#include
#include
#include
int main() {
std::vector<:vector>> vv;
for (std::string line;
std::getline(std::cin, line);
vv.push_back(std::vector(std::istream_iterator(std::move(std::istringstream(line))),
std::istream_iterator()))
);
// Process the vector of vectors vv
}
In this snippet, the 'stay' idiom ensures that the provided lvalue reference remains valid after the move. The move is necessary for efficiency, as it avoids unnecessary character copying.
These solutions provide efficient and versatile methods for extracting integers from a text file and storing them in a vector, regardless of whether the lines have a consistent or varying number of integers.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3