使用C ++格式化文件读取 [英] Formatted file reading with C++

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

问题描述

我试图从一个文件读取所有的整数,并把它们放入一个数组中。我有一个输入文件,其中包含以下格式的整数:

  3 74 

74 1

1 74

8 76

基本上,每行包含一个数字,一个空格,然后是另一个数字。
我知道在Java中我可以使用Scanner方法nextInt()来忽略间距,但是我在C ++中没有找到这样的函数。

解决方案

#include< fstream>
#include< iostream>
#include< vector>

int main()
{
std :: vector< int> ARR;
std :: ifstream f(file.txt);
int i;
while(f>> i)
arr.push_back(i);
}

或者,使用标准算法:

  #include< algorithm> 
#include< fstream>
#include< iterator>
#include< vector>

int main()
{
std :: vector< int> ARR;
std :: ifstream f(file.txt);
std :: copy(
std :: istream_iterator< int>(f)
,std :: istream_iterator< int>()
,std :: back_inserter(arr)
);
}


I am trying to read all integers from a file and put them into an array. I have an input file that contains integers in the following format:

3 74

74 1

1 74

8 76

Basically, each line contains a number, a space, then another number. I know in Java I can use the Scanner method nextInt() to ignore the spacing, but I have found no such function in C++.

解决方案

#include <fstream>
#include <iostream>
#include <vector>

int main()
{
  std::vector<int> arr;
  std::ifstream f("file.txt");
  int i;
  while (f >> i)
    arr.push_back(i);
}

Or, using standard algorithms:

#include <algorithm>
#include <fstream>
#include <iterator>
#include <vector>

int main()
{
  std::vector<int> arr;
  std::ifstream f("file.txt");
  std::copy(
    std::istream_iterator<int>(f)
    , std::istream_iterator<int>()
    , std::back_inserter(arr)
  );
}

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

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