c - 在 C 中使用 isdigits 、 isalpha 和 ispunct

标签 c for-loop counter ctype

我试图通过用户输入来识别字母、数字和标点符号的数量,我得到了数字的数量,但字母和标点符号不正确! .

我不知道为什么.. 这是我的代码

#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/

相关文章:

Java 同步计数器 - get() 怎么样?

loops - Delphi:如何制作鼠标点击计数器?

c - for 循环中的多个测试条件在逻辑上与 && 相关联

c - 如何解决这个C链接器错误?

c - 使用 clang 强制执行 ANSI C89

algorithm - 循环算法设计

Java - 跳过for循环中的值

java - 增强的 for 循环和 float 组

我可以根据 C 标准分配超过 65535 个字节吗?

count_word 函数在 C 中返回 0