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++:
Include the necessary header file: In order to use the
std::stoi()
orstd::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.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 variablestr
and assign the value "123" to it.Convert the string to a number: Use the appropriate conversion function based on the type of number you want to convert to.
- For converting to an integer, use
std::stoi()
. For example,int num = std::stoi(str);
would convert the stringstr
to an integer and assign it to the variablenum
. For converting to a floating-point number, use
std::stod()
. For example,double num = std::stod(str);
would convert the stringstr
to a double and assign it to the variablenum
.Handle exceptions: Both
std::stoi()
andstd::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.