问题
I have a text file which looks like this:
73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85861560789112949495459501737958331952853208805511
and etc. 20 lines in total. What I want to do is to read every digit from the text file and put them into an array of integers(one element = one digit). How can I read only one digit from this text file, not the whole line?
回答1:
There are several ways to accomplish what you are looking for, in this post I'll describe three different methods. All three of them assume that you open your file using an std::ifstream ifs ("filename.txt")
and that your "array" is actually a vector declared as std::vector<int> v
.
At the end of this post there is also a little advice on how to speed up insertion into your vector.
I'd like to keep it simple..
The most simple approach is to read one char
at a time using operator>>
and then subtract '0'
from the value returned.
The standard guarantee that '0'
through '9'
are sequential, and since a char
is nothing but a numeric value printed in a different matter it can implicitly be casted to int
.
char c;
while (ifs >> c)
v.push_back (c - '0');
I love the STL, and hate writing loops..
This will by many be treated as the "c++ way to do it", espacially if you are talking to STL-fanboys, though it requires a lot more code to write..
#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')
);
I don't want to write loops, but why not use a 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';}
);
Will my std::vector
reallocate storage upon each insertion?
Yes, probably. To speed things up you can reserve storage in your vector before you start doing any insertions, as in the below.
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');
来源:https://stackoverflow.com/questions/11119429/c-reading-digits-from-text-file