There are a number of issues with your code. First, you are confusing the char
type (a representation of a printable character, such as the digit '3'
) and the int
type (representing the actual value of a number, and stored as a binary value). In your code, you are attempting to sum the former, where (assuming ASCII representation), the character 2
will have a value of 50
. We can readily address this issue by simply subtracting the value of the '0'
character (ASCII 48
), as the C Standard guarantees that the digits will be represented by consecutive, increasing values.
Another problem is that your code will add each individual digit, so that the 12
in your string will be summed up as 1 + 2
, rather than as 12
. To get round this, we can keep a 'flag' to keep track of whether we are currently 'inside' a number and, if so, first multiply our current number by 10, before adding the new digit.
Also, rather than checking a specific range of non-digit characters, you should use the standard isdigit()
function to check if a character is (not) a decimal number.
There are also a few other issues in your code, which I have addressed in the comments in the "working version" posted below:
#include <stdio.h> // This header for "printf" and "scanf"
#include <ctype.h> // This one for the "isdigit" function!
void function(char a[])
{
// char sum = 0; // Let's use an int for the sum!
int sum = 0, add = 0; // ... and another one for each extracted number to add
// int count = 0; // This is never used
int in_number = 0; // We need a flag to see if we're currently processing a number
for (int i = 0; a[i] != '\0'; i++) {
// if (a[i] >= 'a' && a[i] <= 'z') {
if (!isdigit(a[i])) { // This is better than testing individual character ranges!
if (in_number) { // We have a number to add to our total...
sum += add;
}
add = 0; // Reset the 'next' number to add
in_number = 0; // and clear our 'in_number' flag
// continue; // We don't need this, because the "else" block won't run if we're in here!
}
else { // We've found a digit ...
add *= 10; // First, multiply our current number by 10 (before we add the next digit)
add += a[i] - '0'; // We need to convert the character to a number
in_number = 1; // Don't forget to set our flag to show we're currently in a number!
}
}
// When we've finished our loop, we need to check if we're still inside a number:
if (in_number) {
sum += add;
}
printf("%d", sum); // Use the "%d" format to print an integer!
}
int main()
{
int t;
scanf("%d", &t);
while (t--) {
char a[1000]; // DO you REALLY need a 10001 character buffer?
scanf("%s", a);
function(a);
printf("\n");
}
return 0; // Always good practice to actually have this at the end of your "main"
}
Feel free to ask for any further clarification and/or explanation.