c-编写一个函数,从控制台逐行读取,并打印加载的每一行的字符数



编写一个函数,从控制台逐行读取,并打印加载的每行的字符数。读取的行的最大长度应为20个字符。

我有一些东西只是通过循环,一遍又一遍地打印到输入字符串。我有问题-在每次用户输入后打印字符数,并将最大字符输入设置为20,例如。有人帮我吗?

char str[str_size];
int alp, digit, splch, i;
alp = digit = splch = i = 0;

printf("nnCount total number of alphabets, digits and special characters :n");
printf("--------------------------------------------------------------------n");
do {
printf("Input the string : ");
fgets(str, sizeof str, stdin);
} while (str[i] != '');
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 : %dn", alp + digit + splch);

}

我不明白您如何处理代码中的do while循环。所以我只是为你的案子提出另一个循环。我不确定,但希望代码是你想要的。

int main() {
char str[22];
int alp, digit, splch, i;
printf("nnCount total number of alphabets, digits and special characters :n");
printf("--------------------------------------------------------------------n");
printf("Input the string : ");
while (fgets(str, sizeof str, stdin)){
alp = digit = splch = 0;
for (i = 0; i < strlen(str); i++ ) {
if ((str[i] >= 'a' && str[i] <= 'z') || (str[i] >= 'A' && str[i] <= 'Z'))
{
alp++;
}
else if (str[i] >= '0' && str[i] <= '9')
{
digit++;
}
else if(str[i] != 'n')
{
splch++;
}
}
printf("alp = %d, digit = %d, splch = %dn", alp, digit, splch);
printf("Input the string : ");
}
return 0;
}

OT,为了确定字母或数字,可以使用isdigit()isalpha()函数。它比您在代码中使用的东西更简单。

程序看起来可以像一样

#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" ) ] = '';
for ( const char *p = str; *p != ''; ++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 stringn",
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键,循环就会结束。

请注意,程序将空格和标点符号视为特殊字符。

最新更新