I write function that calculate numbers in string. example: "t5ds5" the program return 10 = 5+5. I got error when I run my program. here the code!
int SumStr(char *str)
{
int i;
int temp = 0;
for(i=0;i<strlen(str);i++)
{
if(*str >= 48 &a开发者_C百科mp;& *str <= 57)
{
temp +=*str;
}
}
printf("%d", temp);
return 0;
}
You are not moving your pointer to the string so you will only check the first value and never any of the other ones. Also you need to shift down from ascii value to the integer value. It should be something like:
if ( str[i] >= 48 && str[i] <= 57 ) {
temp += str[i] - '0';
}
Try this:
int SumStr(char *str)
{
int temp = 0;
while(*str)
{
if((*str >= '0') && (*str <= '9'))
temp += *str - '0';
str++;
}
printf("%d", temp);
return 0;
}
Although this would seem more normal:
int SumStr(char *str)
{
int result = 0;
while(*str)
{
if((*str >= '0') && (*str <= '9'))
temp += *str - '0';
str++;
}
return result;
}
Calling the function with SumStr("t5ds5")
gives the expected result of 10.
Your code wasn't advancing str
so you checked the same character each time round the loop. It also calls strlen()
each time round the loop which makes the algorithm O(n^2) which is not ideal. You may as well walk the string once as per the code above.
As to why your code produced an access violation that must be due to the parts of the code that you haven't shown. One can only imagine that str
must point to an invalid memory address or is not null-terminated.
精彩评论