[英]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 the complex<float>
? 有没有比分割字符串更简单/更快的方法,读取两个值并返回complex<float>
?
Just add the parentheses and the default operator>>
will do it for you: 只需添加括号,默认operator>>
将为您执行:
#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. 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: 如果您已准备好处理异常,也可以使用boost来完成:
std::complex<float> c = boost::lexical_cast<std::complex<float> >('('+s+')');
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. 您可以在字符串周围添加括号,然后类会为您读取数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.