Home >Backend Development >C++ >How to Parse Integers from a Text File in C with ifstream?
Parsing Integers from a Text File in C Using ifstream
In the realm of programming, working with files is a common necessity. One such task involves reading integers from a text file for data analysis or graph construction. Yet, when faced with a text file containing an unknown number of lines, each consisting of a varying number of integers, parsing becomes a challenge.
To address this problem, we can employ the trusty ifstream class and std::getline() function to read lines from the text file. However, line parsing poses a new hurdle. To overcome this, let us delve into two effective approaches:
Using StringStream and While Loop:
This method utilizes the istringstream constructor to parse a line. It reads integers within a while loop, appending them to a vector until newline is encountered:
<code class="cpp">while (std::getline(infile, line)) { std::istringstream iss(line); int n; std::vector<int> v; while (iss >> n) { v.push_back(n); } // Utilize the parsed integer vector 'v' for your desired purpose }</code>
One-Line Solution with std::move:
For a more streamlined approach, we can employ a combination of std::move() and a for loop:
<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>
This solution utilizes the std::stay() function to retain ownership of the input stream, enabling use within the for loop. It iterates over the lines, using std::istream_iterator to parse integers into vector
The above is the detailed content of How to Parse Integers from a Text File in C with ifstream?. For more information, please follow other related articles on the PHP Chinese website!