A numeric string can be converted into an integer type when its value needs to be used in arithmetic or other numeric operations.n C++ provides stol(), stoul(), and atol() for converting strings into signed or unsigned long values.
- stol() converts a std::string to long.
- stoul() converts a std::string to unsigned long, while atol() works with C-style strings.
Examples:
Input: s1 = "20", s2 = "30"
Output: long: 50Input: s = "123456654"
Output: 123456654
Methods to Convert String to Long
The conversion can be performed using the following methods:
1. Using stol()
The std::stol() function converts a std::string containing an integer into a long value.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1 = "20";
string s2 = "30";
// Convert strings to long
long n1 = stol(s1);
long n2 = stol(s2);
// Add the converted values
long result = n1 + n2;
cout << "long: " << result;
return 0;
}
Output
long: 50
Explanation
- stol() converts "20" and "30" into long values.
- The converted values are added to obtain 50.
2. Using stoul()
The std::stoul() function converts a std::string into an unsigned long value. It is suitable for non-negative integer values.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s1 = "20";
string s2 = "30";
// Convert strings to unsigned long
unsigned long n1 = stoul(s1);
unsigned long n2 = stoul(s2);
// Add the converted values
unsigned long result = n1 + n2;
cout << "unsigned long: " << result;
return 0;
}
Output
unsigned long: 50
Explanation
- stoul() converts the numeric strings into unsigned long values.
- The converted values are added to obtain 50.
3. Using atol()
The atol() function converts a C-style string (const char*) containing an integer into a long value. It is available through the <cstdlib> header.
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
const char* str = "123456654";
// Convert C-style string to long
long num = atol(str);
cout << num;
return 0;
}
Output
123456654
Explanation
- atol() accepts a C-style string.
- It converts the numeric text into a long value.
- The converted value is stored in num.