"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Published on 2024-11-20
Browse:858

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.

#include 
#include 
#include 

std::ifstream infile("text_file.txt");
std::string line;

while (std::getline(infile, line)) {
  std::istringstream iss(line);
  int n;
  std::vector v;

  while (iss >> n) {
    v.push_back(n);
  }

  // Process the vector v
}

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:

#include 
#include 
#include 

int main() {
  std::vector<:vector>> vv;

  for (std::string line;
       std::getline(std::cin, line);
       vv.push_back(std::vector(std::istream_iterator(std::move(std::istringstream(line))),
                                     std::istream_iterator()))
       );

  // Process the vector of vectors vv
}

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3