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>
?
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.
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 (-).
std::to_string in C++ The to_string() method takes a single integer variable or other data type and converts into the string.
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+')');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With