【问题标题】:(C++) Reading digits from text file(C++) 从文本文件中读取数字
【发布时间】:2012-06-20 12:20:48
【问题描述】:

我有一个如下所示的文本文件:

73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511

等等总共20行。 我想要做的是从文本文件中读取每个数字并将它们放入一个整数数组中(一个元素=一个数字)。我怎样才能从这个文本文件中只读取一个数字,而不是整行?

【问题讨论】:

  • 使用 fgetc() 读取字符并转换为整数...

标签: c++ file digit


【解决方案1】:

有几种方法可以完成您正在寻找的东西,在这篇文章中,我将描述三种不同的方法。他们三个都假设您使用std::ifstream ifs ("filename.txt") 打开文件,并且您的“array”实际上是一个声明为std::vector<int> v 的向量。

在这篇文章的最后,还有一些关于如何加快插入向量的建议。


我想保持简单..

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

'0''9' 的标准保证是连续的,并且由于 char 只是以不同方式打印的数值,因此可以隐式转换为 int

char c;

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

我喜欢 STL,讨厌写循环......

这将被许多人视为“c++ 实现方式”,尤其是如果您正在与 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?

#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

【讨论】:

    【解决方案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'); 
    

    【讨论】:

      猜你喜欢
      • 2021-12-19
      • 2020-08-16
      • 2012-11-10
      • 1970-01-01
      • 2020-02-24
      • 1970-01-01
      • 1970-01-01
      • 2012-10-29
      • 2023-04-09
      相关资源
      最近更新 更多