Convert float to std::string in C++

前端 未结 8 2018
后悔当初
后悔当初 2020-11-29 02:23

I have a float value that needs to be put into a std::string. How do I convert from float to string?

float val = 2.5;
std::string my_val = val;          


        
8条回答
  •  北荒
    北荒 (楼主)
    2020-11-29 03:19

    You can define a template which will work not only just with doubles, but with other types as well.

    template  string tostr(const T& t) { 
       ostringstream os; 
       os<

    Then you can use it for other types.

    double x = 14.4;
    int y = 21;
    
    string sx = tostr(x);
    string sy = tostr(y);
    

提交回复
热议问题