How to parse a string to an int in C++?

C++Server Side ProgrammingProgramming

You can use a string stream to parse an int in c++ to an int. You need to do some error checking in this method.

example

#include<iostream>
#include<sstream>
using namespace std;

int str_to_int(const string &str) {
   stringstream ss(str);
   int num;
   ss >> num;
   return num;
}

int main() {
   string s = "12345";
   int x = str_to_int(s);
   cout << x;
}

Output

This will give the output −

12345

In the new C++11, there are functions for that: stoi(string to int), stol(string to long), stoll(string to long long), stoul(string to unsigned long), etc.

Example

You can use these functions as follows −

#include<iostream>
using namespace std;

int main() {
   string s = "12345";
   int x = stoi(s);
   cout << x;
}

Output

This will give the output −

12345


raja
Published on 28-Feb-2018 11:14:15
Advertisements