How to convert string to float in C++

5 Answers

0 votes
#include <iostream>
 
int main()
{
   std::string str = "3.14159";
    
   float f = stof(str);
    
   std::cout << f;
} 
   
  
   
   
/*
run:
   
3.14159
   
*/

 



answered Jun 20, 2021 by avibootz
edited Apr 8, 2024 by avibootz
0 votes
#include <iostream>
 
int main()
{
   std::string str = "3.14159";
    
   float f = atof(str.c_str());
    
   std::cout << f;
} 
   
  
   
   
/*
run:
   
3.14159
   
*/

 



answered Apr 8, 2024 by avibootz
0 votes
#include <iostream>
#include <sstream>
 
float convertToFloat(std::string str) {
   float f;
   
   std::stringstream ss(str);
   
   ss >> f;
    
   return f;
}
 
int main()
{
   std::string str = "3.14159";
    
   float f = convertToFloat(str);
    
   std::cout << f;
} 
   
  
   
   
/*
run:
   
3.14159
   
*/

 



answered Apr 8, 2024 by avibootz
0 votes
using std::cout;
using std::endl;
using std::string;
 
int main()
{
    string s = "3.14";
    string::size_type st;
 
    float f = std::stof(s, &st);
 
    cout << f << " size_type: " << st << endl;
}


 
/*
run:
 
3.14 size_type: 4

*/

 



answered Jul 5, 2024 by avibootz
0 votes
#include <iostream>
#include <string>
 
using std::cout;
using std::endl;
 
int main()
{
    const char *s = "3.14";
 
    float f = std::stof(s);
 
    cout << f << endl;
}


 
/*
run:
 
3.14
 
*/

 



answered Jul 5, 2024 by avibootz

Related questions

1 answer 105 views
2 answers 214 views
214 views asked May 16, 2021 by avibootz
2 answers 150 views
2 answers 145 views
2 answers 150 views
150 views asked May 17, 2021 by avibootz
...