C++ Converting a String to Double

后端 未结 3 1223
無奈伤痛
無奈伤痛 2020-12-17 03:54

I\'ve been trying to find the solution for this all day! You might label this as re-post but what I\'m really looking for is a solution without using boost lexical c

3条回答
  •  天涯浪人
    2020-12-17 04:36

    Since C++11 you could use std::stod function:

    string line; 
    double lineconverted;
    
    try
    {
        lineconverted = std::stod(line);
    }
    catch(std::invalid_argument)
    {
        // can't convert
    }
    

    But solution with std::stringstream also correct:

    #include 
    #include 
    #include 
    
    int main()
    {
        std::string str;
        std::cin >> str;
        std::istringstream iss(str);
        double d = 0;
        iss >> d;
        std::cout << d << std::endl;
        return 0;
    }
    

提交回复
热议问题