Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

Read integers from a text file with C++ ifstream

I want to read graph adjacency information from a text file and store it into a vector.

  • the file has arbitrary number of lines

  • each line has arbitrary number of integers ended with ' '

for example,

First line:
0 1 4
Second line:
1 0 4 3 2
Thrid line:
2 1 3
Fourth line:
3 1 2 4
Fifth line:
4 0 1 3

If I use getline() to read one line at a time, how do I parse the line (as each line has variable number of integers)?

Any suggestions?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The standard line reading idiom:

#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
}

Here's a one-line version using a for loop. We need an auxiliary construction (credits to @Luc Danton!) that does the opposite of std::move:

namespace std
{
  template <typename T> T & stay(T && t) { return t; }
}

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>())
                    )
       ) { }

  std::cout << vv << std::endl;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...