Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,990 questions

51,935 answers

573 users

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 122 views
2 answers 229 views
229 views asked May 16, 2021 by avibootz
2 answers 165 views
2 answers 163 views
2 answers 170 views
170 views asked May 17, 2021 by avibootz
...