Home > Backend Development > C++ > body text

How to Efficiently Parse Integers from a Text File with Varying Counts into a Vector in C ?

Patricia Arquette
Release: 2024-10-30 19:54:30
Original
495 people have browsed it

How to Efficiently Parse Integers from a Text File with Varying Counts into a Vector in C  ?

Reading Integers from a Text File with C ifstream

When attempting to read graph adjacency information from a text file, one can encounter lines with varying counts of integers terminated by 'n'. Using the getline() method to retrieve each line individually poses the challenge of accurately parsing each line due to its inconsistent number of integers. Strategies are sought to address this issue and efficiently store these values in a vector.

The conventional approach calls for iterating over each line read by getline() and utilizing an istringstream object to parse each line. As integers are read sequentially, they can be appended to a vector, which can then be further manipulated as desired. The following code exemplifies this approach:

<code class="cpp">#include <fstream>
#include <sstream>
#include <string>
#include <vector>

int main() {
  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 with v
  }
}</code>
Copy after login

An alternative solution involves a single-line for loop. By utilizing the istream_iterator class, we can read values directly into a vector, reducing the need for intermediary containers. An auxiliary function is also employed to prevent the potential dangling references that could arise from std::move.

<code class="cpp">#include <fstream>
#include <string>
#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::stay(std::istringstream(line))),
                                     std::istream_iterator<int>())
                    )
       ) { }
}</code>
Copy after login

The above is the detailed content of How to Efficiently Parse Integers from a Text File with Varying Counts into a Vector in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template