In C++, you can convert different data types to an integer using the stoi()
function from the <string>
library.
Here’s an example of how to use stoi()
to convert a string to an integer:
#include <iostream>
#include <string>
int main() {
std::string str = "123";
int num = std::stoi(str);
std::cout << num << std::endl;
return 0;
}
In this example, we declare a std::string
variable named str
and initialize it with the value "123"
. We then use the std::stoi()
function to convert str
to an integer and store the result in an int
variable named num
. Finally, we print the value of num
to the console using std::cout
.
You can also use stoi()
to convert other data types to integers, such as char
, double
, and float
. Here’s an example of how to use stoi()
to convert a char
to an integer:
#include <iostream>
#include <string>
int main() {
char c = '5';
int num = std::stoi(std::string(1, c));
std::cout << num << std::endl;
return 0;
}
In this example, we declare a char
variable named c
and initialize it with the value '5'
. We then use std::string(1, c)
to convert c
to a std::string
, and pass the resulting string to std::stoi()
to convert it to an integer.
Note that when converting a char
to a std::string
, we pass 1
as the first argument to std::string()
to indicate that we want to create a string of length 1 containing the character c
.
Overall, the stoi()
function is a useful way to convert different data types to integers in C++.