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]);
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