example3_string2number_viceversa.cpp

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <sstream>
#include <iomanip>

int main() {
    // String to number conversion
    std::string str_num = "123.456";
    std::istringstream iss(str_num);
    double number;
    iss >> number;
    
    std::cout << "Converted string to number: " << number << std::endl;
    
    // Number to string conversion with formatting
    double pi = 3.14159265359;
    std::ostringstream oss;
    oss << std::fixed << std::setprecision(2) << pi;
    std::string str_pi = oss.str();
    
    std::cout << "Converted number to string with 2 decimal places: " << str_pi << std::endl;
    
    return 0;
}
Back to sstream