使用C ++ ifstream从文本文件读取整数 [英] Read integers from a text file with C++ ifstream

查看:1704
本文介绍了使用C ++ ifstream从文本文件读取整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从文本文件中读取图形邻接信息并将其存储到向量中。




  • 行数


  • 每行都有以'\\\
    '结尾的任意数字整数




例如,

 第一行:
0 1 4
第二行:
1 0 4 3 2
第三行:
2 1 3
第四行:
3 1 2 4
第五行:
4 0 1 3



如果我使用getline



有没有建议?

解决方案

标准行阅读习语:

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

//对v
使用有用的操作
$ b


$ b b




这是一个单行版本,使用来循环。我们需要一个辅助结构(信用@ @ Luc Danton !)与 std :: move

 命名空间std 
{
template<类型名T> T&留(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> :: istream_iterator< int>(std :: stay(std :: istringstream(line))),
std :: istream_iterator< int>())

){}

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


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 '\n'

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?

解决方案

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

这篇关于使用C ++ ifstream从文本文件读取整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆