string to decimal

hi
how do i convert a string to decimal value?
i read in a string "20" , how do i convert it from string to decimal.. does reading it as a string assume its hex?
what if i want the hex value? and then convert to decimal
thanks
atoi converts a string to an int. It assumes the number is decimal and starts with +/- or a number. Any other initial characters causes it to return zero.

If you want to convert using another base, such as 16, you may have to do it yourself, but it's not hard.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iostream>
#include <string>
#include <ctype.h>

long string2long(const std::string &str, int base = 10)
{
	long result = 0;

	if (base < 0 || base > 36)
		return result;

	for (size_t i = 0, mx = str.size(); i < mx; ++i)
	{
		char ch = tolower(str[i]);
		int num = 0;

		if ('0' <= ch && ch <= '9')
			num = (ch - '0');
		else if ('a' <= ch && ch <= 'z')
			num = (ch - 'a') + 10;
		else
			break;

		if (num > base)
			break;

		result = result*base + num;
	}

	return result;
}

int main()
{
	std::string str("Z");
	std::cout << string2long(str, 36) << std::endl;
	std::cout << string2long(str, 2) << std::endl;

	return 0;
}
1
2
3
4
#include <cstdlib>

int strtol( const char* nptr, char **endptr, int base );


set base = 16 and it does what you want.
Topic archived. No new replies allowed.