我有一个如下所示的文本文件:
73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511
等等。总共20行。我想要做的是从文本文件中读取每个数字并将它们放入一个整数数组中(一个元素=一个数字)。我怎样才能从这个文本文件中只读取一个数字,而不是整行?
有几种方法可以完成您正在寻找的东西,在这篇文章中,我将描述三种不同的方法。他们三个都假设您使用 an 打开文件,std::ifstream ifs ("filename.txt")并且您的“数组”实际上是一个声明为std::vector<int> v.
在这篇文章的最后,还有一些关于如何加快插入向量的建议。
最简单的方法是char一次读取一个operator>>,然后'0'从返回的值中减去。
标准保证'0'through'9'是顺序的,并且由于 achar只是以不同方式打印的数值,因此可以隐式转换为int.
char c;
while (ifs >> c)
v.push_back (c - '0');
这将被许多人视为“ 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')
);
#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
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');