How to use sprintf In C++
By specifying the precision in sprintf, we can convert double to string or character array with custom precision. We can use sprintf to add extra text (as required) to the string at the same time.
C++
// C++ Program to demonstrate Double to // String Conversion using sprintf #include <cstring> #include <iostream> #include <string> #define Max_Digits 10 using namespace std; int main() { double N = 1243.3456; char str[Max_Digits + sizeof ( char )]; std:: sprintf (str, "%f" , N); std:: printf ( "string is: %s \n" , str); return 0; } |
Output
string is: 1243.345600
C++ Program For Double to String Conversion
Here, we will build a C++ program for double to string conversion using various methods i.e.
- Using to_string
- Using stringstream
- Using sprintf
- Using lexical_cast
We will keep the same input in all the mentioned approaches and get an output accordingly.
Input:
n = 456321.7651234
Output:
string: 456321.7651234
Contact Us