C++ Converting a String to Double

后端 未结 3 1222
無奈伤痛
無奈伤痛 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:19
    #include <sstream>
    
    int main(int argc, char *argv[])
    {
        double f = 0.0;
    
        std::stringstream ss;
        std::string s = "3.1415";
    
        ss << s;
        ss >> f;
    
        cout << f;
    }
    

    The good thing is, that this solution works for others also, like ints, etc.

    If you want to repeatedly use the same buffer, you must do ss.clear in between.

    There is also a shorter solution available where you can initialize the value to a stringstream and flush it to a double at the same time:

    #include <sstream>
    int main(int argc, char *argv[]){
       stringstream("3.1415")>>f ;
    }
    
    0 讨论(0)
  • 2020-12-17 04:30

    If you want to store (to a vector for example) all the doubles of a line

    #include <iostream>
    #include <vector>
    #include <iterator>
    
    int main()
    {
    
      std::istream_iterator<double> in(std::cin);
      std::istream_iterator<double> eof;
      std::vector<double> m(in,eof);
    
      //print
      std::copy(m.begin(),m.end(),std::ostream_iterator<double>(std::cout,"\n"));
    
    }
    
    0 讨论(0)
  • 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 <sstream>
    #include <string>
    #include <iostream>
    
    int main()
    {
        std::string str;
        std::cin >> str;
        std::istringstream iss(str);
        double d = 0;
        iss >> d;
        std::cout << d << std::endl;
        return 0;
    }
    
    0 讨论(0)
提交回复
热议问题