代码之家  ›  专栏  ›  技术社区  ›  Burkhard

如何将字符串转换成复杂的<浮点> C++?

  •  4
  • Burkhard  · 技术社区  · 16 年前

    如何轻松地将包含两个由逗号分隔的浮点数的字符串转换为复数?

    例如:

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

    有没有比拆分字符串、读取两个值并返回 complex<float> ?

    2 回复  |  直到 16 年前
        1
  •  10
  •   Cubbi    16 年前

    只需添加括号和默认值 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";
    }
    

    有趣的是,每个人的风格都略有不同,尽管答案是一样的。

        std::complex<float> c = boost::lexical_cast<std::complex<float> >('('+s+')');