Home >Backend Development >C++ >How to Read Integers from a Text File with Variable-Length Lines in C ?

How to Read Integers from a Text File with Variable-Length Lines in C ?

DDD
DDDOriginal
2024-10-29 16:30:02756browse

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!

Statement:
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