string to number in c++

To convert a string to a number in C++, you can use the std::stoi() or std::stod() functions, depending on whether you want to convert to an integer or a floating-point number, respectively. Here are the steps to convert a string to a number in C++:

  1. Include the necessary header file: In order to use the std::stoi() or std::stod() functions, you need to include the <string> header file in your code. This provides the necessary functions and data types for working with strings.

  2. Declare a string variable: Create a string variable and assign the string that you want to convert to it. For example, std::string str = "123"; would create a string variable str and assign the value "123" to it.

  3. Convert the string to a number: Use the appropriate conversion function based on the type of number you want to convert to.

  4. For converting to an integer, use std::stoi(). For example, int num = std::stoi(str); would convert the string str to an integer and assign it to the variable num.
  5. For converting to a floating-point number, use std::stod(). For example, double num = std::stod(str); would convert the string str to a double and assign it to the variable num.

  6. Handle exceptions: Both std::stoi() and std::stod() may throw an exception if the conversion fails. You can catch these exceptions using a try-catch block to handle any errors that may occur during the conversion.

Here's an example code snippet that demonstrates the conversion of a string to an integer in C++:

#include <iostream>
#include <string>

int main() {
    std::string str = "123";

    try {
        int num = std::stoi(str);
        std::cout << "Number: " << num << std::endl;
    } catch (const std::exception& e) {
        std::cout << "Conversion failed: " << e.what() << std::endl;
    }

    return 0;
}

This code snippet converts the string "123" to an integer using std::stoi() and then prints the converted number. If the conversion fails, it catches the exception thrown by std::stoi() and prints an error message.