c - 在 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;
}
解决方案
这个循环
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] ) )
否则,如果字符代码为负,则通常不强制转换此类调用可能会调用未定义的行为。
推荐阅读
- android - Android:当应用程序在后台时,防止屏幕上弹出数据通知
- angular - 有没有如何在 AG-GRID 上显示行时获取行?
- azure - 有没有办法让 LUIS 应用程序连接到 SQL 服务器
- amazon-web-services - 如何获取 S3 存储桶中所有先前版本对象的总存储量
- php - SQL 中的 PHP 引号
- postgresql - PostgreSQL - 存储 IMEI 号码的最佳方式(不摆脱铅 0)
- excel - VBA For Next 循环遍历一个范围
- google-colaboratory - 在哪里可以找到安装在 google Colab 中的现有包
- node.js - 如何在节点js中将数据从页面传输到另一个页面
- google-calendar-api - Google Calendar API:带有休息日属性的假日活动