Mastering C++ Conversions: A Comprehensive Guide
Unlocking the Power of String Conversions
When working with C++, converting between data types is an essential skill to master. In this article, we’ll explore the easiest ways to convert strings to floating-point numbers and vice versa, using the latest C++11 functions.
Effortless String to Float and Double Conversions
The C++11 standard library provides three convenient functions to convert strings to floating-point numbers:
std::stof()
for converting strings to floatsstd::stod()
for converting strings to doublesstd::stold()
for converting strings to long doubles
These functions are defined in the string header file, making it easy to incorporate them into your projects.
Example 1: C++ String to Float and Double Output
Let’s see these functions in action:
“`cpp
include
include
int main() {
std::string strFloat = “3.14”;
std::string strDouble = “3.14159”;
float f = std::stof(strFloat);
double d = std::stod(strDouble);
std::cout << "Float: " << f << std::endl;
std::cout << "Double: " << d << std::endl;
return 0;
}
“`
Converting Char Arrays to Double
But what about char arrays? We can use the std::atof()
function to convert them to doubles:
“`cpp
include
include
int main() {
char strDouble[] = “3.14159”;
double d = std::atof(strDouble);
std::cout << "Double: " << d << std::endl;
return 0;
}
“`
The Reverse Conversion: Float and Double to String
Now, let’s explore how to convert float and double values back to strings. The C++11 std::to_string()
function makes it easy:
“`cpp
include
include
int main() {
float f = 3.14;
double d = 3.14159;
std::string strFloat = std::to_string(f);
std::string strDouble = std::to_string(d);
std::cout << "Float: " << strFloat << std::endl;
std::cout << "Double: " << strDouble << std::endl;
return 0;
}
“`
Older C++ Compilers? No Problem!
For older C++ compilers, we can use std::stringstream
objects to achieve the same result:
“`cpp
include
include
int main() {
float f = 3.14;
double d = 3.14159;
std::stringstream ss;
ss << f;
std::string strFloat = ss.str();
ss.str(""); // clear the stringstream
ss << d;
std::string strDouble = ss.str();
std::cout << "Float: " << strFloat << std::endl;
std::cout << "Double: " << strDouble << std::endl;
return 0;
}
“`
With these techniques under your belt, you’ll be able to effortlessly convert between strings and floating-point numbers in your C++ projects.