首页 > 解决方案 > 编写一个函数,从控制台逐行读取并打印加载的每一行的字符数

问题描述

编写一个函数,从控制台逐行读取并打印加载的每一行的字符数,正在读取的行的最大长度应为 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);


}

标签: ccharfgetsc-stringscounting

解决方案


该程序似乎可以如下所示

#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 键,循环就会结束。

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


推荐阅读