2
作爲賦值的一部分,我必須編寫一個程序從用戶處獲取一個字符串,並輸出該字符串中的字母數以及總和該字符串中的數字。例如,如果我要輸入abc123
作爲我的字符串,程序應該告訴我,有3個字母,數字的總和是6
(3 + 2 + 1)。程序必須使用核心函數(即函數相互調用)。我的代碼到目前爲止如下:添加數字和字符串的計數字符(分段錯誤)
#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"
),則會出現分段錯誤。任何關於我在做什麼的想法都是錯誤的?我認爲這個問題與我的循環邏輯有關,但我不是100%確定的。
我無法重現OP的問題。 –
@iharob:我剛剛糾正了我答案中的一個錯誤,但問題肯定存在。當我嘗試「g3」時,'countAlph'調用'sumDigits',它調用'countAlph',調用'sumDigits',等等。當你嘗試時會發生什麼? – Beta
是的。我剛剛測試了'g3'並重現了Stack Overflow。 –