[英]why is my strcmp ending my program abruptly?
#include <stdio.h>
#include <string.h>
void processString(char *str, int *totVowels, int *totDigits);
int main()
{
char str[50], *p;
int totVowels, totDigits;
printf("Enter the string: \n");
fgets(str, 80, stdin);
if (p = strchr(str, '\n')) *p = '\0';
processString(str, &totVowels, &totDigits);
printf("Total vowels = %d\n", totVowels);
printf("Total digits = %d\n", totDigits);
return 0;
}
void processString(char *str, int *totVowels, int *totDigits)
{
int i, j;
char tester[11] = {'a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U'};
*totDigits = 0;
*totVowels = 0;
for (i = 0; i < strlen(str); i++)
{
if (isdigit(str[i]))
{
*totDigits += 1;
}
else if(isalpha(str[i]))
{
for (j = 0; j < 11; j++)
{
if (strcmp(str[i], tester[j]) == 0)
{
*totVowels+=1;
}
}
}
}
}
我的代码试图计算数字和元音出现在字符串中的次数。
我的字符串比较试图检查元音,但程序在到达strcmp
行时结束。 为什么会这样? 我的语法错了吗?
PS我只允许在processString
函数中编辑,其余的都给了。
您的问题在于代码if (strcmp(str[i], tester[j]) == 0)
。 因为您正在引用一维数组,所以取消引用结果是单个字符。 本质上,您是在比较两个chars
,并且可以比较chars
是否相等,例如ints
。 , not single chars
.并且strcmp
设计用于比较,而不是单个chars
。 这就是它出现段错误的原因(段错误是由于无效的指针取消引用造成的。在这种情况下,它试图取消引用一个非指针。一个明确的禁忌。)
解决方法是将该行替换为: if (str[i] == tester[j])
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.