-->

(C ++)从文本文件中读取数字((C++) Reading digits from text fi

2019-06-25 15:04发布

我有一个文本文件,它看起来像这样:

73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511

等20条线的总额。 我想要做的就是读取文本文件中的每个数字,把它们放到一个整数数组(一个元素=一个数字)。 如何从这个文本文件,而不是整个行只读一个数字吗?

Answer 1:

有几种方法来完成你在找什么,在这篇文章中,我将介绍三种不同的方法。 他们三个假设你使用打开文件std::ifstream ifs ("filename.txt")和你的“ 阵列 ”,实际上是宣布为载体std::vector<int> v

在这篇文章的末尾也有关于如何插入加快到您的载体一点建议。


我想保持简单..

最简单的方法是读取一个char同时使用operator>> ,然后减去'0' ,从返回的值。

该标准保证'0''9'是连续的,且由于char只不过是在一个不同的问题可以被隐式铸造印刷数值int

char c;

while (ifs >> c)
  v.push_back (c - '0');

我爱STL,恨编写循环..

这将被许多人视为“C ++的方式做到这一点 ”,espacially如果你谈论到STL-的fanboys,但它需要更多的代码来写..

#include <algorithm>
#include <functional>
#include <iterator>

...

std::transform (
  std::istream_iterator<char> (ifs),
  std::istream_iterator<char> (), 
  std::back_inserter (v),
  std::bind2nd (std::minus<int> (), '0')
);

我不想写循环,但为什么不使用lambda? C ++ 11

#include <algorithm>
#include <functional>
#include <iterator>

...

std::transform (
  std::istream_iterator<char> (iss),
  std::istream_iterator<char> (),
  std::back_inserter (v),
  [](char c){return c - '0';}
);

将我std::vector重新分配在每次插入存储?

应该是。 为了加快速度,你可以保留存储在您的载体你开始做任何插入之前,如在下面。

ifs.seekg (0, std::ios::end); // seek to the end of your file
v.reserve (ifs.tellg ()    ); // ifs.tellg () -> number of bytes in it
ifs.seekg (0, std::ios::beg); // seek back to the beginning


Answer 2:

char digit;
std::ifstream file("digits.txt");
std::vector<int> digits;
// if you want the ASCII value of the digit.
1- while(file >> digit) digits.push_back(digit);
// if you want the numeric value of the digit.
2- while(file >> digit) digits.push_back(digit - '0'); 


文章来源: (C++) Reading digits from text file
标签: c++ file digit