Wednesday, April 29, 2009

Convert Std String to Integer in C++

In C++ there are no methods/functions to convert std string to integer. But, by using C standard library (cstdlib or stdlib.h) we can convert char* (C string) to integer using atoi function. We can also convert string to char* (C string) using c_str function in string class. Thus, we can convert string to integer via char*. This is the function (I call as stoi) and the example:

#include <iostream>
#include <cstdlib>

using namespace std;

int stoi(string _str) {
 return atoi(_str.c_str());
}

int main() {
 string current_year = "2009";
 string birth_year = "1987";
 int age = stoi(current_year) - stoi(birth_year);
 cout << "Age = " << age << " years old" << endl;
 
 return 0;
}

Output:

Age = 22 years old

No comments:

Post a Comment