Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string to complex<float> in C++?

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>?

like image 313
Burkhard Avatar asked Aug 05 '10 10:08

Burkhard


People also ask

How do you concatenate a string and complex number in Python?

Python does not allow the concatenation of strings with numbers or numbers with numbers. However, you can convert a numeric value into a string using the str() method and then perform concatenation.

What does to_ string return in c++?

std::to_string Returns a string with the representation of val. Decimal-base representation of val. The representations of negative values are preceded with a minus sign (-).

What is to_ string?

std::to_string in C++ The to_string() method takes a single integer variable or other data type and converts into the string.


1 Answers

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+')');
like image 79
Cubbi Avatar answered Nov 06 '22 04:11

Cubbi