Home >Backend Development >C++ >How to Read Integers from a Text File with Variable-Length Lines in C ?
Read Integers from a Text File with C ifstream
When dealing with text files containing variable-length lines of integers, the standard line reading idiom proves useful:
<code class="cpp">#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 }</code>
This approach uses getline to read each line and istringstream to parse the integers within each line.
Alternatively, a more concise one-line solution utilizes a for loop and the stay auxiliary template:
<code class="cpp">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>()) ) ) { }</code>
Both approaches effectively parse the variable-length integer sequences from the input text file.
The above is the detailed content of How to Read Integers from a Text File with Variable-Length Lines in C ?. For more information, please follow other related articles on the PHP Chinese website!