Sum of C-String Integers

Jan 22, 2009 at 3:23pm
I have an array of chars where I am requiring the user to enter any number of consecutive integers (ex: 12345) with no spaces. I am attempting to output the sum of all the numbers. My problem is it's adding up the ascii instead of the actual number. Is there a way I can convert the c-string to integers during the addition itself?

Edit: Trying to use atoi function but it doesn't seem to work in the format below. How can I loop through each char in the array and cast it as an integer?

1
2
	for ( int i = 0; i <= strlen(digits); i++ )
		total += atoi(digits[i]);



Thanks,
Return 0;
Last edited on Jan 22, 2009 at 3:37pm
Jan 22, 2009 at 4:58pm
Your string holds characters, as you yourself suggest, i.e. '0' for 0, '3' for 3, etc. If you consult an ASCII character map you will find that the char values for '0'-'9' are all in consequtive places from 0x30 onwards, so if you have a char '7' (actually 0x37) and you subtract the char '0' (actually 0x30) from it, you will get the result 7.

So you can get a digit's value from a char by subtracting '0' or 0x30 from it. The rest is up to you :D
Jan 22, 2009 at 9:06pm
You can convert strings to integers via stringstreams
eg:
1
2
3
4
char* n="12345";
int i;
stringstream ss(n);
ss >> i;// i now == 12345 
Jan 23, 2009 at 2:18am
the problem is that atoi() requires a null-terminated string as argument, but you are passing a character.

if you make the char a string and pass it to atoi it should work

e.g.

1
2
3
4
5
6
7
char mydigit[2] = {0};

for ( int i = 0; i < strlen(digits); i++ ) // note '<' and not '<='
{
  mydigit[0] = digits[i];
  total += atoi( mydigit );
}
Last edited on Jan 23, 2009 at 2:44am
Topic archived. No new replies allowed.