Mark As Completed Discussion

String Conversion

Converting strings to other data types and vice versa is a common task in programming. In C++, you can convert a string to an integer using the std::stoi function and to a double using the std::stod function.

Here's an example:

TEXT/X-C++SRC
1#include <iostream>
2#include <sstream>
3#include <string>
4
5int main() {
6    std::string str = "12345";
7
8    // Converting string to int
9    int num = std::stoi(str);
10    std::cout << "String to int: " << num << std::endl;
11
12    // Converting string to double
13    double decimal = std::stod(str);
14    std::cout << "String to double: " << decimal << std::endl;
15
16    // Converting int to string
17    int number = 67890;
18    std::string result = std::to_string(number);
19    std::cout << "Int to string: " << result << std::endl;
20
21    // Converting double to string
22    double pi = 3.14159;
23    std::ostringstream oss;
24    oss << pi;
25    std::string strpi = oss.str();
26    std::cout << "Double to string: " << strpi << std::endl;
27
28    return 0;
29}

In this example, we have a string str with the value "12345". We use the std::stoi function to convert it to an integer, and the std::stod function to convert it to a double. We also demonstrate converting an integer and a double back to strings using the std::to_string function and ostringstream respectively.

String conversion is useful in various scenarios, for example, when you need to process user input, parse data from files, or convert numeric values to strings for output. It allows you to work with different data types and perform operations specific to those types.

Keep in mind that the conversion functions may throw exceptions if the conversion fails. It's a good practice to handle possible exceptions to ensure your program behaves correctly.

CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment