添加字符串的数字和计数字母(分段错误)

时间:2015-10-27 01:22:22

标签: c string segmentation-fault

作为作业的一部分,我必须编写一个程序,从用户那里获取一个字符串,并打印出该字符串中的字母数,以及该字符串中数字的总和。例如,如果我输入abc123作为我的字符串,程序应该告诉我有3个字母,并且数字的总和是6(3 + 2 + 1)。程序必须使用corecursive函数(即函数相互调用)。到目前为止,我的代码如下:

#include <stdio.h>
#include <string.h>

//Function prototypes
void countAlph(char str[], int, int);
void sumDigits(char str[], int, int);

int main(void)
{
    //Create an array that can hold 25 characters
    char anStr[25];
    int inputSize;

    //Get string from user
    printf("Enter an alphanumeric string:\n");
    scanf("%s", anStr);

    //Get size (# of elements in the array)
    inputSize = strlen(anStr);

    //Function call
    countAlph(anStr, inputSize, 0); //pass the string, size of the string, and 0 (first index position)
}

//function that counts # of letters
void countAlph(char str[], int size, int currentIndex)
{
    //use ASCII codes!

    int alphaCount = 0, i;

    if(currentIndex < size)
    {
        for(i=0; i<size; i++)
        {
            if((str[i] >= 65 && str[i] <= 90) || (str[i] >= 97 && str[i] <= 122)) //if element is a letter
            {
                alphaCount++; //increase # of letters by 1
            }
            else if(str[i] >= 48 && str[i] <= 57) //if element is NOT a letter
            {
                sumDigits(str, size, i); //go to the sumDigits function
            }
        }
    }
    printf("There are %d letters in this string\n", alphaCount);
}

//function that adds all the digits together
void sumDigits(char str[], int size, int currentIndex)
{
    //use ASCII codes!

    int sum = 0, i;

    if(currentIndex < size)
    {
        for(i=0; i<size; i++)
        {
            if(str[i] >= 48 && str[i] <= 57) //if element is a digit
            {
                //I found the line of code below online after searching how to convert from ASCII to int
                str[i] = str[i] - '0'; //this converts the ascii value of the element to the decimal value
                sum = sum + str[i]; //add that digit to the running sum
            }
            else if((str[i] >= 65 && str[i] <= 90) || (str[i] >= 97 && str[i] <= 122)) //if element is NOT a number
            {
                countAlph(str, size, i); //go to the countAlph function
            }
        }
    }
    printf("The sum of the digits of this string is %d\n", sum);
}

如果我的字符串只包含数字或仅包含字母,我的程序可以正常工作。但是如果我输入一个字母数字字符串,例如"abc123",我会遇到分段错误。关于我做错了什么的任何想法?我认为这个问题与我的循环逻辑有关,但我不是百分之百确定。

1 个答案:

答案 0 :(得分:2)

你的两个职能互相打电话。每一个都将currentIndex传递给另一个,但每个都忽略了从另一个获取的currentIndex并从i = 0开始。

因此,如果你给它一个字母到字母到数字的转换(例如“g3”),那么这两个函数会相互调用,直到它们重载调用栈为止。

一个解决方案:让使用 currentIndex

另一种解决方案:在一个功能中处理字母和数字。