I implemented the following code, which does what it's supposed to, but I think that it can / should be simplified.
Basically, I need to create a vector of numbers, each containing one of the digits found in testString. Is there any way to construct the stringstream directly from a char (i. e. testString[i])? I'd rather not involve C-style functions, like atoi, if it can be done in a C++ way.
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
int main ()
{
std::string testString = "abc123.bla";
std::string prefix = "abc";
std::vector<unsigned short> digits;
if (0 == testString.find(prefix))
{
for (size_t i = prefix.size(); i < testString.find("."); ++i)
{
int digit;
std::stringstream digitStream;
digitStream << testString[i];
digitStream >> digit;
digits.emplace_back(digit);
}
}
for (std::vector<unsigned short>::iterator digit = digits.begin(); digit < digits.end(); ++digit)
{
std::cout << *digit << std::endl;
}
return 0;
}
Assuming testString[i]
is between '0'
and '9'
, just do:
digits.emplace_back(testString[i] - '0');