Convert String to Double in C++
Convert String to Double in C++ (6 Programs).
1#include <iostream>2#include <string>3#include <sstream>4using namespace std;56int main() {7 string str = "123.456";89 // Method 1: Using stod()10 double num1 = stod(str);1112 // Method 2: Using stringstream13 stringstream ss(str);14 double num2;15 ss >> num2;1617 cout << "String: " << str << endl;18 cout << "Double (method 1): " << num1 << endl;19 cout << "Double (method 2): " << num2 << endl;2021 return 0;22}
Output
String: 123.456 Double (method 1): 123.456 Double (method 2): 123.456
What's going on
The program converts a string like "123.456" into a double value 123.456. This conversion is necessary because:
Example:
Header Files Used
Declaring Variables
The program declares:
string str = "123.456";
Method 1: Using stod() (String to Double)
double num1 = stod(str);
This is the most modern and recommended method in C++:
How it works:
Advantages:
Example:
double d1 = stod("123.456"); // 123.456
double d2 = stod("1.23e2"); // 123.0 (scientific notation)
double d3 = stod(" 45.67 "); // 45.67 (whitespace handled)
Method 2: Using stringstream
stringstream ss(str);
double num2;
ss >> num2;
This method uses stringstream, which treats a string like an input stream:
How it works:
Advantages:
Example for multiple values:
stringstream ss("123.45 67.89 10.11");
double a, b, c;
ss >> a >> b >> c; // a=123.45, b=67.89, c=10.11
Other Methods (Mentioned but not shown in code)
Method 3: Using atof() (C-style)
double num3 = atof(str.c_str());
1#include <cstdlib>
Method 4: Using sscanf() (C-style)
double num4;
sscanf(str.c_str(), "%lf", &num4);
1#include <cstdio>
Method 5: Using strtod() (C-style)
char* endPtr;
double num5 = strtod(str.c_str(), &endPtr);
1#include <cstdlib>
Method 6: Manual Conversion
double num6 = 0.0;
double sign = 1.0;
int i = 0;
if (str[0] == '-') { sign = -1.0; i = 1; }
// Convert integer part
while (i < str.length() && str[i] != '.') {
num6 = num6 * 10 + (str[i] - '0');
i++;
}
// Convert decimal part
if (i < str.length() && str[i] == '.') {
i++;
double fraction = 0.1;
while (i < str.length()) {
num6 += (str[i] - '0') * fraction;
fraction /= 10;
i++;
}
}
num6 *= sign;
1// Handle negative sign
How Manual Conversion Works (Step-by-Step)
Understanding manual conversion helps you understand the concept:
For string "123.456":
The process:
Displaying Results
The program prints:
Output:
String: 123.456
Double (method 1): 123.456
Double (method 2): 123.456
Both methods produce the same double value.
1cout << "String: " << str << endl;2cout << "Double (method 1): " << num1 << endl;3cout << "Double (method 2): " << num2 << endl;
Precision and Accuracy
Double precision
: double can represent approximately 15-17 significant digits
Floating-point limitations
:
For exact decimal arithmetic
: Consider using decimal libraries or fixed-point arithmetic for financial applications.
Error Handling
Different methods handle errors differently:
stod()
: Throws std::invalid_argument or std::out_of_range exceptions
try {
double num = stod("abc");
} catch (const std::exception& e) {
}
1// Handle error
atof()
: Returns 0.0 for invalid input (no way to distinguish error from actual 0.0)
strtod()
: Sets endPtr to indicate where conversion stopped
char* endPtr;
double num = strtod("123.45abc", &endPtr);
if (*endPtr != '0') {
}
1// Partial conversion or error
stringstream
: Sets failbit on error
if (ss.fail()) {
}
1// Handle error
Best Practice
: Use stod() with try-catch for robust error handling.
When to Use Each Method
-
stod()
: Best for most cases - simple, safe, modern C++
-
stringstream
: Best when converting multiple values or mixing types
-
atof()
: Only for legacy code - no error checking
-
strtod()
: When you need C compatibility with better error handling
-
sscanf()
: When you need complex format parsing
-
Manual
: For learning or when you need custom conversion logic
return 0;
This ends the program successfully.