简体   繁体   中英

Construct stringstream from char

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 (ie 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;
}

假设testString[i]'0''9' ,那么就这样做:

digits.emplace_back(testString[i] - '0');

See my original comment ; subtract '0' from each digit character.

#include <string>
#include <vector>
#include <algorithm>
#include <iterator>
#include <cctype>
#include <functional>
#include <iostream>

...

std::string input = "abc123.bla";
std::string prefix = "abc";
std::vector<unsigned short> digits;

auto input_b = input.begin();
std::copy_if(input_b, std::find(input_b, input.end(), '.'),
    std::back_inserter(digits), (int (*)(int)) std::isdigit);

auto digits_b = digits.begin();
auto digits_e = digits.end();
std::transform(digits_b, digits_e, digits_b,
    std::bind2nd(std::minus<unsigned short>(), '0'));
std::copy(digits_b, digits_e,
    std::ostream_iterator<unsigned short>(std::cout, "\n"));

It can even be shortened if you don't need digits to contain the intermediate digit values.

std::transform(digits.begin(), digits.end(),
    std::ostream_iterator<unsigned short>(std::cout, "\n"),
    std::bind2nd(std::minus<unsigned short>(), '0'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM