When you code in C++, sometimes you need to convert one data type to another.
This article will introduce two commonly used methods to convert strings to integers using C++.
Before learning methods, you must first understand the data types of C++.
1. Data types in C++
The C++ programming language has some built-in data types:
int
, for integers (e.g. 10, 150)double
, for floating point numbers (e.g. 5.0, 4.5)char
, for a single character (e.g. "D", "!")string
, for character sequences (e.g. "Hello")bool
, for boolean values (true or false)
C++ is a strongly typed programming language, which means that when you create a variable, you must explicitly declare what type of value will be stored in it.
2. How to convert string to integer
Method 1: Use the stoi() function to convert the string into an integer. This is a valid approach and works with newer versions of C++, introduced starting with C++11. It accepts a string as input and returns its integer form as output.
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "7";
cout << "我是一个字符串 " << str << endl;
int num = stoi(str);
cout << "我是一个整数 " << num << endl;
}
Output result:
I am a string 7
I am an integer 7
Method 2: Use the stringstream class to convert the string into an integer. This approach mainly works with older versions of C++. It does this by inputting and outputting strings.
First, you need to add #include <sstream> at the top of the program to include the sstream library.
Then create a stringstream object that holds the value of the string you want to convert to an integer and use it during the conversion.
You can use <<
operators to extract strings from string variables.
Finally, >>
the newly converted int value is entered into the int variable using the operator.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main() {
stringstream ss;
string str = "7";
int num;
ss << str;
ss >> num;
cout << num << endl;
}
Now that you know two simple ways to convert a string to an integer in C++, you can try some more.