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.
<code class="cpp">#include <fstream> #include <sstream> #include <vector> std::ifstream infile("text_file.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); } // Process the vector v }</code>
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:
<code class="cpp">#include <sstream> #include <iterator> #include <vector> 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::move(std::istringstream(line))), std::istream_iterator<int>())) ); // Process the vector of vectors vv }</code>
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.
The above is the detailed content of How to Efficiently Read Integers from a Text File with Varying Integer Counts Using C ifstream?. For more information, please follow other related articles on the PHP Chinese website!