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
Release: 2024-10-29 16:30:02
Original
764 people have browsed it

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

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

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!

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