我试图通过用户输入来识别字母、数字和标点符号的数量,我得到了数字的数量,但字母和标点符号不正确! .
我不知道为什么.. 这是我的代码
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int main()
{
char str[50];
int alphabet = 0 , number = 0, punct = 0;
printf("Enter your sentence: ");
fgets(str, sizeof(str),stdin);
for(int i=0 ; i<50; i++)
{
if(isalpha(str[i]) != 0)
{
alphabet++;
}
else if (isdigit(str[i]) != 0 ){
number++;
}
else if (ispunct(str[i]) != 0){
punct++;
}
}
printf("Your sentence contains:\n");
printf("Alphabets: %d",alphabet);
printf("\nDigits: %d",number);
printf("\nPunctuation: %d",punct);
return 0;
}
最佳答案
这个循环
for(int i=0 ; i<50; i++)
不正确。输入的字符串可以小于字符数组str
的大小。
所以改用
for( size_t i = 0 ; str[i] != '\0'; i++ )
考虑到函数fgets
可以附加换行符
\n'
到输入的字符串。如果你想在循环之前删除它,那么写
#include <string.h>
//…
str[strcspn( str, "\n" )] = '\0';
此外,在 if 语句中,您应该将给定字符转换为 unsigned char
类型。例如
if( isalpha( ( unsigned char )str[i] ) != 0)
或
if( isalpha( ( unsigned char )str[i] ) )
否则,如果字符的代码为负数,一般来说,如果不进行强制转换,此类调用可能会调用未定义的行为。
关于c - 在 C 中使用 isdigits 、 isalpha 和 ispunct,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59693967/