views:

60

answers:

2

How do I easily convert a string containing two floats separated by a comma into a complex?

For instance:

string s = "123,5.3";//input
complex<float> c(123,5.3);//output/what I need

Is there an simpler/faster way than to split the string, read the two values and return thecomplex<float>?

+4  A: 

Just add the parentheses and the default operator>> will do it for you:

#include <iostream>
#include <string>
#include <complex>
#include <sstream>
int main()
{
        std::string s = "123,5.3";//input

        std::istringstream is('(' + s + ')');
        std::complex<float> c;
        is >> c;

        std::cout << "the number is " << c << "\n";
}

PS. Funny how everyone's style is slightly different, although the answers are the same. If you are ready to handle exceptions, this can be done with boost, too:

    std::complex<float> c = boost::lexical_cast<std::complex<float> >('('+s+')');
Cubbi
Exactly what I need. Thanks.
Burkhard
+1  A: 

The complex class has an extraction operator. You could add parentheses around the string, and then the class would read in the number for you.

cHao