convert a string position to int?

Mar 29, 2012 at 11:56pm
Hey guys, I'm encountering a problem when trying to convert a specific index of a string (like s1[x]) to an int.

After some searching I found methods such as atoi and stringstream to convert entire strings to an int, however those methods don't seem to work for individual positions.

can anyone please suggest what methods should I use?
1
2
3
4
5
6
7
string input;
int arr[100];

	stringstream convert(input[x]);
			convert>>arr[x];

Last edited on Mar 30, 2012 at 12:10am
Mar 30, 2012 at 12:13am
input[x] gives you a char. So you want to convert a char to an int.

Do you want the ASCII (or whatever encoding you are using) value? Then all you have to do is
arr[x] = input[x];
or if you want to be explicit
arr[x] = static_cast<int>(input[x]);

If input is storing only digits and you want to convert the digits to int you can just subtract '0' from the ASCII value. That will give you the integer value.
arr[x] = input[x] - '0';
Last edited on Mar 30, 2012 at 12:14am
Mar 30, 2012 at 12:22am
thanks a lot! I got it to work now!
Topic archived. No new replies allowed.