The string is a primitive data type, mainly used to take the user input or store the data consisting of multiple characters. Strings are one of the most commonly used data types by programmers.
But, sometimes they have to be converted into a float as per the requirements of the application or software development environment.
Float is also the primitive data type in C++. It is used to store the numerical values up to the certain decimal points. It is preferable in scientific calculations as they require maximal decimal arithmetic methods. Float is used in daily life applications like calculators and others for the calculations of numbers that involve decimal values.
Why Is There A Need To Convert String To Float In C++
Some reasons are explained below. This will help us to understand the importance of the “How to convert string to float in C++”.
- Mathematical calculations – Some programs need mathematical calculations to be done. This calculation can be in decimals. The string is not designed for mathematical calculations.
- To take the user input – Programmers have to design programs that have to get the decimal numerical from the users such as the value of pi. To get this value they have to convert the string to float.
- Output presentation – Whenever a user requests sensible data. Then the conversion of the string into the float is a must.
Different Approaches To Convert String To Float In C++
There can be many approaches to convert the string data into floats using various header files and functions. Some of them are explained below.
- Using stof function
- Using atof function
- Using stringstream object
- Using sscanf function
- Using strtod function
- Using Boost.Lexical_Cast library
Lets dive in details for each approach.
Approach 1 : Convert string to float in C++ using stof function
The stof function is the method from the <string> header file which converts string data into float. These functions take the string variable as an argument to achieve the conversion.
Sample code :
// import necessary header files
#include <iostream>
#include <string>
int main() {
// define a string
std::string str = "3.14";
// define float value and convert string to float using the method
float f = std::stof(str);
// print the output on the console
std::cout << "The string \"" << str << "\" is equivalent to the float " << f << std::endl;
return 0;
}
Output :
The string "3.14" is equivalent to the float 3.14
Explanation :
- Import the <string> header file to apply the method
- Define the string for the conversion
- Create a float variable and use the method
- Print the output on the console
Approach 2 : Convert string to float in C++ using atof function
The <cstdlib> header file contains the atof function which converts the string data into float. This approach contains straightforward syntax to achieve the conversion. The <cstdlib> library should be imported to apply the function.
Sample code :
// import necessary header files
#include <iostream>
#include <cstdlib>
#include <string>
int main() {
// define a string
std::string str = "3.14";
// define float value and convert string to float using the method
float f = std::atof(str.c_str());
// print the output on the console
std::cout << "The string \"" << str << "\" is equivalent to the float " << f << std::endl;
return 0;
}
Output :
The string "3.14" is equivalent to the float 3.14
Explanation :
- Import the <string> and <cstdlib> header file to apply the method
- Define the string for the conversion
- Create a float variable and use the method
- Print the output on the console
Approach 3 : Convert string to float in C++ using stringstream object
The stringstream object is the method from <sstream> header file which converts string data into float. These functions take the string variable as an argument to achieve the conversion.
Sample code :
// import necessary header files
#include <iostream>
#include <sstream>
#include <string>
int main() {
// define a string
std::string str = "3.14";
// define float value and convert string to float using the method
std::stringstream ss(str);
float f;
ss >> f;
// print the output on the console
std::cout << "The string \"" << str << "\" is equivalent to the float " << f << std::endl;
return 0;
}
Output :
The string "3.14" is equivalent to the float 3.14
Explanation :
- Import the <string> and <sstream> header files to apply the method
- Define the string for the conversion
- Create a float variable and use the method
- Print the output on the console
- // import necessary header files
- #include <iostream>
- #include <cstdio>
- #include <string>
- int main() {
- // define a string
- std::string str = “3.14”;
- // define float value and convert string to float using the method
- float f;
- std::sscanf(str.c_str(), “%f”, &f);
- // print the output on the console
- std::cout << “The string \”” << str << “\” is equivalent to the float ” << f << std::endl;
- return 0;
- }
Approach 4 : Convert string to float in C++ using sscanf function
The <cstdio> header file contains the sscanf function which converts the string data into float. This approach contains straightforward syntax to achieve the conversion. The <cstdio> library should be imported to apply the function.
Sample code :
// import necessary header files
#include <iostream>
#include <cstdio>
#include <string>
int main() {
// define a string
std::string str = "3.14";
// define float value and convert string to float using the method
float f;
std::sscanf(str.c_str(), "%f", &f);
// print the output on the console
std::cout << "The string \"" << str << "\" is equivalent to the float " << f << std::endl;
return 0;
}
Output :
The string "3.14" is equivalent to the float 3.14
Explanation :
- Import the <string> and <cstdio> header files to apply the method
- Define the string for the conversion
- Create a float variable and use method
- Print the output on the console
Approach 5 : Convert string to float in C++ using strtod function
The strtod function is the method from <cstdlib> header file which converts string data into float. These functions take the string variable as an argument to achieve the conversion. If the condition is used to check the invalid string data.
Sample code :
// import necessary header files
#include <iostream>
#include <cstdlib>
#include <string>
int main() {
// define a string
std::string str = "3.14";
char* end;
// define float value and convert string to float using the method
float f = std::strtod(str.c_str(), &end);
if (*end != '\0') {
std::cerr << "Error: Invalid string format" << std::endl;
return 1;
}
// print the output on the console
std::cout << "The string \"" << str << "\" is equivalent to the float " << f << std::endl;
return 0;
}
Output :
The string "3.14" is equivalent to the float 3.14
Explanation :
- Import the <string> and <cstdlib> header files to apply the method
- Define the string for the conversion
- Create a float variable and use method
- Print the output on the console
Approach 6 : Convert string to float in C++ using Boost.Lexical_Cast library
The <boost/lexical_cast.hpp> header file contains the lexical_cast<float>() function which converts the string data into float. This approach contains straightforward syntax to achieve the conversion. The <boost/lexical_cast.hpp> library should be imported to apply the function.
This function requires an external library <boost/lexical_cast.hpp>, which should be downloaded and installed separately. Hence, this approach code is not supported by online compilers. This method is not meant for beginners.
Sample code :
// import necessary header files
#include <iostream>
#include <string>
#include <boost/lexical_cast.hpp>
int main() {
// define a string
std::string str = "3.14";
// define float value and convert string to float using the method
float f = boost::lexical_cast<float>(str);
// print the output on the console
std::cout << "The string \"" << str << "\" is equivalent to the float " << f << std::endl;
return 0;
}
Output :
The string "3.14" is equivalent to the float 3.14
Explanation :
- Import the <string> and <boost/lexical_cast.hpp> header files to apply the method
- Define the string for the conversion
- Create a float variable and use method
- Print the output on the console
Best Approach Out Of Six for Converting String To Float In C++
The stof function is the method from the <string> header file and can be considered the best approach for different reasons. Some are stated below –
- Syntax – The syntax of the stof function is predefined and very simple to understand. This also helps to apply the syntax in any C++ program.
- Beginner friendly – This approach is very beginner friendly and helps individuals to apply the method in the application development in the initial stages.
- No external resource dependency- This approach is in-built in C++ programming. Hence, it doesn’t require any external library to run the conversion.
Sample Problems
Sample problem 1:
Create a C++ program for the fitness company that takes the weight in kilograms of the particular person and stores it in the application’s database.
Solution :
- Important the necessary header files for the approach
- Define string and float variable
- Get the user input for the conversion
- Create a try-catch block to avoid any errors and it ensures the successful running of code
- Use the method and print the output
Code :
// import necessary header files
#include <iostream>
#include <string>
using namespace std;
int main() {
// define a string and float
string str;
float f;
// get the user input for the conversion
cout << "Enter your weight: ";
cin >> str;
try {
// use the method and print it on the console
f = stof(str);
cout << "Your weight is: " << f << endl;
} catch (const std::invalid_argument& ia) {
cerr << "Invalid argument: " << ia.what() << endl;
} catch (const std::out_of_range& oor) {
cerr << "Out of range: " << oor.what() << endl;
}
return 0;
}
Output :
Enter your weight: 56.5
Your weight is: 56.5
Sample problem 2:
Problem statement
Create a C++ program for the super shop that takes the manufacturing cost of the particular item and stores it in the application’s database. Also, print the cost in float on the console using the atof function.
Solution :
- Import the <string> and <cstdlib> header file to apply the method
- Get the cost of the item through cin
- Create a float variable and use method
- Print the output on the console
Code :
// import necessary header files
#include <iostream>
#include <cstdlib>
#include <string>
int main() {
// define a string
std::string str;
// get the cost of the item
std::cout << "Enter cost of the item: ";
std::cin >> str;
// use the method and print the output on the console
float f = std::atof(str.c_str());
std::cout << "The item cost \"" << str << "\" is equivalent to the float " << f << std::endl;
return 0;
}
Output :
Enter cost of the item: 26.5
The item cost "26.5" is equivalent to the float 26.5
Sample problem 3:
Create a C++ program for the school that takes the height in inches of the particular student and stores it in the school’s database. Also, print the height on the console using stringstream object.
Solution :
- Import the <string> and <sstream> header files to apply the method
- Define the string and float for the conversion
- Take the student’s height as the user input
- Use the method for the conversion
- Print the output on the console
Code :
// import necessary header files
#include <iostream>
#include <string>
#include <sstream>
int main() {
// define a string and float
std::string str;
float f;
// take the student's height
std::cout << "Enter the height of the student: ";
std::cin >> str;
// use the method and print the output on the console
std::stringstream ss(str);
ss >> f;
std::cout << "You entered the height is " << f << std::endl;
return 0;
}
Output :
Enter the height of the student: 5.6
You entered the height is 5.6
Sample problem 4:
Create a C++ program for the college that takes the percentage of the particular student and stores it in the college’s database. Also, print the percentage on the console using the sscanf function.
Solution :
- Import the <string> and <cstdio> header files to apply the method
- Define the string for the conversion
- Take the input as a percentage of student
- Create a float variable and use method
- Print the output on the console
Code :
// import necessary header files
#include <iostream>
#include <cstdio>
#include <string>
int main() {
// define a string
std::string str;
// take the student's percentage
std::cout << "Enter a percentage: ";
std::cin >> str;
// define the float variable
float f;
// use the method and print the output on the console
std::sscanf(str.c_str(), "%f", &f);
std::cout << "The string \"" << str << "\" is equivalent to the float " << f << std::endl;
return 0;
}
Output :
Enter a percentage: 76.6
The string "76.6" is equivalent to the float 76.6
Sample problem 5:
Create a C++ program for the railway department that takes the tax on the particular item sold at the railway station and stores the tax rate in the railway’s database. Also, print the tax rate on the console using the strtod function.
Solution :
- Import the <string> and <cstdlib> header files to apply the method
- Define the string for the conversion
- Take the tax rate from the railway department
- Create a float variable and use method
- Confirm whether a conversion is done or not
- Print the output on the console
Code :
// import necessary header files
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <string>
int main() {
// define a string
// Use cin to get user input as a string
std::string input;
std::cout << "Enter the tax rate on the item: ";
std::cin >> input;
// Use strtod method to convert the string to a float
char* end;
double f = strtod(input.c_str(), &end);
// Check if the conversion was successful or not and print it on the console
if (end == input.c_str() + strlen(input.c_str())) {
std::cout << "The input \"" << input << "\" is equivalent to the float " << f << std::endl;
} else {
std::cout << "Error: \"" << input << "\" is not a valid floating-point number" << std::endl;
}
return 0;
}
Output :
Enter the tax rate on the item: 5.5
The input "5.5" is equivalent to the float 5.5
Sample problem 6:
Create a C++ program for the municipal corporation that takes the area in a square meter of the particular plot and stores it in the department’s database. Also, print the area on the console using Boost.Lexical_Cast library.
Solution :
- Import the <string> and <boost/lexical_cast.hpp> header files to apply the method
- Define the string for the conversion
- Take the land area in square meters as the input
- Create a float variable and use method
- Use the try-catch block to run the code in a better error-handling environment
- Print the output on the console
Code :
// import necessary header files
#include <iostream>
#include <string>
#include <boost/lexical_cast.hpp>
int main() {
// define a string
std::string str;
// take the value of land's area in square meters
std::cout << "Enter the area of the land: ";
std::cin >> str;
// define the float variable
float f;
// use the try-catch block for the successful conversion
try {
f = boost::lexical_cast<float>(str);
} catch (const boost::bad_lexical_cast& e) {
std::cerr << "Error: " << e.what() << std::endl;
return 1;
}
std::cout << "You entered the area of the land is: " << f << std::endl;
return 0;
}
Output :
Enter the area of the land: 540.4
You entered the area of the land is: 540.4
Conclusion
Converting the string data into float can be an essential task for the programmer while developing the application which represents its data in float data type. Many real-life examples of the conversion are considered above through detailed explanations and sample problems.
Different approaches are discussed for the programmers and the best approach is considered as the suggestion for the beginners. Sample problems will help to deep dive into the approaches and practice the code.