Convert string (char *) to integer
/*
* StrToInt.cpp
*
* Created on: Apr 12, 2012
* Author: Kiran Hegde
*/
#include <iostream>
using namespace std;
int strToInt(const char *str) {
bool isNeg = false;
int index = 0;
if (str[0] == '-') {
isNeg = true;
index++;
}
int num = 0;
while (str[index] != '\0') {
num = (num*10) + (str[index++] - '0');
}
if (isNeg) {
num = -num;
}
return num;
}
/*
* Test the function
*/
int main() {
const char *test = "-423456";
cout << "String: " << test << endl;
cout << "Integer: " << strToInt(test) << endl;
}