convert float to string c++ code example
Example 1: how to change a string to an float in c++
#include <iostream>
#include <string>
int main() {
std::string str = "123.4567";
float num_float = std::stof(str);
double num_double = std::stod(str);
std:: cout<< "num_float = " << num_float << std::endl;
std:: cout<< "num_double = " << num_double << std::endl;
return 0;
}
Example 2: to_string c++
#include <iostream>
#include <string>
int main ()
{
std::string pi = "pi is " + std::to_string(3.1415926);
std::string perfect = std::to_string(1+2+4+7+14) + " is a perfect number";
std::cout << pi << '\n';
std::cout << perfect << '\n';
return 0;
}
Example 3: cpp float to string
#include <sstream>
std::ostringstream ss;
ss << myFloat;
std::string s(ss.str());