c - 编写一个函数,从控制台逐行读取并打印加载的每一行的字符数
问题描述
编写一个函数,从控制台逐行读取并打印加载的每一行的字符数,正在读取的行的最大长度应为 20 个字符。
我有一些东西只是通过循环并一遍又一遍地打印到输入字符串。我遇到问题 - 在每次用户输入后打印字符数并将最大字符输入设置为 20 例如。有人帮我吗?
char str[str_size];
int alp, digit, splch, i;
alp = digit = splch = i = 0;
printf("\n\nCount total number of alphabets, digits and special characters :\n");
printf("--------------------------------------------------------------------\n");
do {
printf("Input the string : ");
fgets(str, sizeof str, stdin);
} while (str[i] != '\0');
if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z'))
{
alp++;
}
else if (str[i] >= '0' && str[i] <= '9')
{
digit++;
}
else
{
splch++;
}
i++;
printf("Number of Alphabets in the string is : %d\n", alp + digit + splch);
}
解决方案
该程序似乎可以如下所示
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main(void)
{
enum { str_size = 22 };
char str[str_size];
puts( "\nCount total number of alphabets, digits and special characters");
puts( "--------------------------------------------------------------");
while ( 1 )
{
printf( "\nInput a string less than or equal to %d characters (Enter - exit): ",
str_size - 2 );
if ( fgets( str, str_size, stdin ) == NULL || str[0] == '\n' ) break;
unsigned int alpha = 0, digit = 0, special = 0;
// removing the appended new line character by fgets
str[ strcspn( str, "\n" ) ] = '\0';
for ( const char *p = str; *p != '\0'; ++p )
{
unsigned char c = *p;
if ( isalpha( c ) ) ++alpha;
else if ( isdigit( c ) ) ++digit;
else ++special;
}
printf( "\nThere are %u letters, %u digits and %u special characters in the string\n",
alpha, digit, special );
}
return 0;
}
程序输出可能看起来像
Count total number of alphabets, digits and special characters
--------------------------------------------------------------
Input a string less than or equal to 20 characters (Enter - exit): April, 22, 2020
There are 5 letters, 6 digits and 4 special characters in the string
Input a string less than or equal to 20 characters (Enter - exit):
如果用户只需按下 Enter 键,循环就会结束。
请注意,程序将空格和标点字符视为特殊字符。
推荐阅读
- ios - 我需要帮助使用 Swift 4 格式化文本字段中的小数位
- string - 组装 8086 TASM - 0Ah 21h 记住最后一个条目
- regex - 正则表达式区分字符串中的所有字符与少数字符大写
- android - GoogleAuthException:未知
- unit-testing - 有没有办法配置一个 runsettings 文件只检查被测的实际项目?
- javascript - AG-GRID & AngularJS - 如何在外部编辑数据
- python - 将参数传递给 tkinter 中的函数
- php - 如何仅在选中时显示按钮
- android - 从 LiveData 触发第二个查询并合并结果(Firestore)?
- android - Firebase toObject 与 ref