![](/img/trans.png)
[英]Why is my code only counting the frequency of lower case letters from my string
[英]Why is my program counting letters and digits not running?
我编写了这个函数来检查字符串中的大写、小写和数字,但是当我尝试运行代码时,它会弹出并且似乎无法理解问题。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define size 50
void statistics(char str[], int *lower, int *upper, int *digits) {
for (int i = 0; i < size; i++) {
if (islower(str[i]) != 0) {
*lower = *lower + 1;
} else
if (isupper(str[i]) != 0) {
*upper = *upper + 1;
} else
if (isalpha(str[i])) {
*digits = *digits + 1;
}
}
}
int main() {
char str[size] = { " " };
int upper = 0, lower = 0, digits = 0;
printf("Enter a string:\n");
gets_s(str);
statistics(&str[size], &lower, &upper, &digits);
printf("Lower: %d\nUpper: %d\nDigits %d", lower, upper, digits);
return 0;
}
您的代码中有多个问题:
gets_s()
函数不可移植:它是可选的,在许多系统上不受支持。 您忘记传递数组大小,从而导致未定义的行为。 编译器应该输出一个你不应该忽略的诊断。 您应该改用fgets()
。
您不应将char
值传递给isupper()
和类似函数,因为它们仅针对unsigned char
类型的值和特殊的负值EOF
定义。 使用unsigned char
变量或将str[i]
参数转换为(unsigned char)str[i]
。
您传递 char 数组末尾的地址而不是开头。 只需将str
作为参数传递给statistics
。 statistics
函数读取数组末尾以外的字符,调用未定义的行为,其中一个字节恰好是小于-1
的负char
值,从而触发 Visual C++ 编译器运行时中的诊断。 错误消息很难解释,IDE 应该将您指向调用代码。
您迭代整个数组,超出空终止符。 数组的内容在gets_s()
或fgets()
设置的空终止符之外未定义。 只需停在空终止符处。
你测试if (isalpha(ch))
你可能打算使用if (isdigit(ch))
isxxx
函数为真返回非零值,为假返回零。 在 C 中,只写if (isdigit(c))
而不是if (isdigit(c) != 0)
似乎是多余的,这是惯用的。
将size
定义为宏很容易出错。 使用大写和更明确的名称。
这是修改后的版本:
#include <ctype.h>
#include <stdio.h>
#define LINE_SIZE 50
void statistics(const char *str, int *lower, int *upper, int *digits) {
while (*str != '\0') {
unsigned char ch = *str++;
if (islower(ch)) {
*lower += 1;
} else
if (isupper(ch)) {
*upper += 1;
} else
if (isdigit(ch) {
*digits += 1;
}
}
}
int main() {
char str[LINE_SIZE];
int upper = 0, lower = 0, digits = 0;
printf("Enter a string:\n");
if (fgets(str, sizeof str, stdin)) {
statistics(str, &lower, &upper, &digits);
printf("Lower: %d\nUpper: %d\nDigits %d", lower, upper, digits);
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.