Convert String to Integer in C++
In C++, you can convert a string to an integer using several methods. In this tutorial, we will explore some of the most common methods to perform this conversion.
Syntax
#include <string>
#include <cstdlib>
// Using stoi:
int i = std::stoi("123");
// Using atoi:
int i = std::atoi("123");
// Using stringstream:
int i;
std::stringstream("123") >> i;
Example
Using stoi
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "123";
int num = stoi(str);
cout << "The integer is: " << num << endl;
return 0;
}
Using atoi
#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
char str[] = "123";
int num = atoi(str);
cout << "The integer is: " << num << endl;
return 0;
}
Using stringstream
#include <iostream>
#include <sstream>
using namespace std;
int main() {
string str = "123";
int num;
stringstream ss(str);
ss >> num;
cout << "The integer is: " << num << endl;
return 0;
}
Output
The integer is: 123
Explanation
In all three examples, we start with a string containing an integer value. We then use different methods to convert this string to an integer.
std::stoi
is a C++11 function that accepts a string as input and returns an integer.
std::atoi
is a function in the C standard library that converts a string to an integer.
std::stringstream
is a class in the C++ standard library that allows us to read from and write to strings as if they were streams.
Use
Converting a string to an integer is useful when we need to perform arithmetic operations on a string that contains numerical data. We can also use this conversion to validate user input, as we can easily check if the input is a valid integer by attempting to convert it to one.
Important Points
- C++ provides several methods to convert a string to an integer.
- These methods include
std::stoi
,std::atoi
, andstd::stringstream
. - Converting a string to an integer is useful when we need to perform arithmetic operations on a string that contains numerical data.
- We can also use this conversion to validate user input.
Summary
In summary, we can convert a string to an integer in C++ using several methods. These methods include std::stoi
, std::atoi
, and std::stringstream
. Converting a string to an integer is useful when we need to perform arithmetic operations on a string that contains numerical data or validate user input.