I would split it up into chars, but that's just me.
For example:
- Read in the number as a whole string, not int by int, for this you can use something like scanf or fgets.
- Then go through char by char, each char, subtract the char '0' - subtracting the char 0 (not the numerical value of 0) will convert each char into a number, you can simply tack that number onto a larger counter, ie. If the number is < 0 or > 9, then it's invalid.
You know the string size by using a strlen() funct
Code:
int total_val = 0;
int str_size = strlen(str_buff);
int i;
while (i = 0 ; i < str_size ; ++i)
total_val += str_buff[i] - '0';
The code to get it into string form may look something like.
Now you need to check for bad input, so what you can do is simply:
Code:
int total_val = 0;
int str_size = strlen(str_buff);
int ch;
int i;
for (i = 0 ; i < str_size ; ++i)
{
ch = str_buff[i] - '0';
if (ch < 0 || ch > 9)
{
printf("Invalid Entry\n");
break;
}
total_val += ch;
}
That algorithm works, I tested it just now. Obviously you can set a boolean error flag or something so it doesn't print the total value upon error.