首页 > 解决方案 > 在 C 中使用 isdigits 、 isalpha 和 ispunct

问题描述

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

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

#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;
}

标签: cfor-loopcounterctype

解决方案


这个循环

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 语句中,您应该将给定的字符转换为 type unsigned char。例如

   if( isalpha( ( unsigned char )str[i] ) != 0)

或者

   if( isalpha( ( unsigned char )str[i] ) )

否则,如果字符代码为负,则通常不强制转换此类调用可能会调用未定义的行为。


推荐阅读