I’m getting the following compile error in the marked lines:
error: conversion from ‘
std::basic_ostream<char,’ to non-scalar type ‘
std::char_traits<char> >std::ostringstream’
requested
Could you help me to correct my example?
#include <numeric>
#include <sstream>
using namespace std;
ostringstream ConvertLettersToNumbers(ostringstream acc, char input)
{
if(isdigit(input))
{
return acc << input; // error
}
else
{
return acc << static_cast<int>(input); // error
}
};
int main(int argc, char **argv)
{
string stringToCovert = "ABC";
ostringstream out = accumulate(stringToCovert.begin(), stringToCovert.end(),
string(), ConvertLettersToNumbers);
string convertedString = out.str(); // expected "656667"
return 0;
}
EDIT: My first version using strings that works but is slow:
string ConvertLettersToNumbers(string acc, char input)
{
if(isdigit(input))
{
return acc + input;
}
else
{
stringstream sstr;
sstr << static_cast<int>(input);
return acc + sstr.str();
}
};
Use a different algorithm. You don’t want to add elements together (that is what
accumulateis for), you want totransformyour sequence into another kind of sequence.Consider this approach:
For a working sample see here