I have a text file which looks like this:
73167176531330624919225119674426574742355349194934 96983520312774506326239578318016984801869478851843 85
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.
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');
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')
);
#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
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
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');