JustSomeGuy said:
I have a string that looks like:
"123.45:123.45"
I am using sscanf "%f%*c%f" to extract the two floats and ignore the colon.
However there may be more than two floats....
Is there perhaps a better way to do this in C++?
Like make the string appear as a stream and do it with operator>>
string x;
float f1, f2;
x >> f1;
x >> f2;
I recently refactored this ugly code:
typedef std::map<string, string> params_t;
bool
Product(params_t & testCase)
{
double num (strtod(testCase["Input1" ].c_str(), NULL));
double den (strtod(testCase["Input2"].c_str(), NULL));
double quo (strtod(testCase["Product()" ].c_str(), NULL));
return num * den == quo;
}
It now looks like this:
static double
getDouble(params_t & testCase, string columnName)
{
double num(double());
std::stringstream z (testCase[columnName]);
if (z >> num)
return num;
return 0.0; // TODO will throw soon
}
bool
Product(params_t & testCase, string & because)
{
double num (getDouble(testCase, "Input1" ));
double den (getDouble(testCase, "Input2" ));
double quo (getDouble(testCase, "Product()"));
return num * den == quo;
}
Focus on the 'streamstring z' deep inside. One might extract your floats
using:
string x;
stringstream z(x);
double f1, f2;
char space;
z >> f1;
z >> space;
z >> f2;
BTW use 'double' without a reason to use 'float', just as one uses 'int'
without a reason to use 'short' or 'long'. On modern CPUs 'double's can be
faster, too.
My refactor replaced redundant calls to strtod() (another way to do it) with
a single call to operator>>().