Home > Backend Development > C++ > How to Efficiently Read Integers from a Text File with Varying Integer Counts Using C ifstream?

How to Efficiently Read Integers from a Text File with Varying Integer Counts Using C ifstream?

DDD
Release: 2024-11-02 18:20:29
Original
755 people have browsed it

How to Efficiently Read Integers from a Text File with Varying Integer Counts Using C   ifstream?

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>
Copy after login

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>
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template