简体   繁体   English

在 C 中使用 isdigits 、 isalpha 和 ispunct

[英]using isdigits , isalpha, and ispunct in C

I'm trying to identify the number of alphabets, number and punctuation by the user input , I got the No. of number but the alphabets and punctuation is incorrect!!我正在尝试通过用户输入来识别字母、数字和标点符号的数量,我得到了数字编号,但字母和标点符号不正确!! . .

i'm not sure why.. this is my code我不知道为什么..这是我的代码

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

This loop这个循环

for(int i=0 ; i<50; i++)

is incorrect.是不正确的。 The entered string can be less than the size of the character array str .输入的字符串可以小于字符数组str的大小。

So instead use所以改为使用

for( size_t i = 0 ; str[i] != '\0'; i++ )

Take into account that the function fgets can append the new line character \\n' to the entered string.考虑到函数fgets可以将换行符\\n'附加到输入的字符串。 If you want to remove it before the loop then write如果你想在循环之前删除它然后写

#include <string.h>

//…

str[strcspn( str, "\n" )] = '\0';

Also in if statements you should convert the given character to the type unsigned char .同样在 if 语句中,您应该将给定的字符转换为unsigned char类型。 For example例如

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

or或者

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

Otherwise in general without casting such a call can invoke undefined behavior if the code of a character is negative.否则,如果字符的代码为负,则通常不强制转换此类调用可能会调用未定义的行为。

You have hardcoded the upper boundary of the loop: for(int i=0 ; i<50; i++) , however can you guarantee your input is 49 characters long?您已经对循环的上边界进行了硬编码: for(int i=0 ; i<50; i++) ,但是您能保证您的输入长度为 49 个字符吗? If you cannot, then you will be reading garbage values past '\\0' inserted by fgets.如果不能,那么您将读取 fgets 插入的 '\\0' 之后的垃圾值。 Either change the loop (for example): for(int i=0; i<50 && str[i]; i++) so that you only loop through to the end of the input.要么更改循环(例如): for(int i=0; i<50 && str[i]; i++)以便您只循环到输入的末尾。

Alternatively, zero-initialize the input buffer, ie char str[50] = {0};或者,零初始化输入缓冲区,即char str[50] = {0}; , I believe isalpha(), isdigit() and ispunct() all return false with a zero input, therefore not affecting your results. ,我相信 isalpha()、isdigit() 和 ispunct() 都返回 false,输入为零,因此不会影响您的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM