My updated string to int function

#include <iostream>
#include <string>
#include <cstring>
#include <cctype>
using namespace std;

/* 
 * stoi by Jakash3
 * Converts a string to integer using specified base
 * and integer type template.
 * if base is 0, the base is then determined by a 0x, 0
 * or no prefix in the string.
 */
template <typename T>
T stoi(const char* s, int base) {
	T num = 0;
	bool negative = false;
	static const char digits[] = "0123456789abcdefghijklmnopqrxtuvwxyz";
	
	/* Skip leading whitespace */
	while (isspace(*s)) s++;
	
	/* Check for sign */
	if (*s == '-') { negative = true; s++; }
	else if (*s == '+') s++;
	
	/* Check for base prefix */
	if (*s == '0') {
		s++;
		if (*s == 'x' || *s == 'X') {
			if (base == 0) base = 16;
			else if (base != 16) return 0;
			s++;
		} else if (isdigit(*s)) {
			if (base == 0) base = 8;
		} else if (*s == 0) return 0;
	} else if (*s == 0) return 0;
	else if (base == 0) base = 10;
	
	/* Loop through each digit */
	for (int digit; *s; s++) {
	
		/* Look for digit in the list of digits */
		const char *where = strchr(digits, tolower(*s));
		
		/* Check for valid digit */
		if (where == NULL) break;
		digit = where - digits;
		if (digit >= base) break;
		
		/* Shift the number and add the new digit */
		num  = num * base + digit;
	}
	
	/* Handle negative numbers */
	if (negative) return -num;
	
	/* Done */
	return num;
}

int main() {
	string s;
	cout << "Enter a number: ";
	getline(cin, s);
	cout << stoi<int>(s.c_str(), 0) << endl;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: