【问题标题】:Array reads whitespace and control char数组读取空格和控制字符
【发布时间】:2021-05-13 12:06:04
【问题描述】:
char str[100];    
fgets(str,100,stdin);
int i;
int alpha=0;    
int space=0;
int cntrl=0;
while(str[i])
{
     if(isalpha(str[i]))
     {
        printf("%c is an alphabet\n",str[i]);
        alpha++;
     }
     if(isspace(str[i]))
     {
        printf("%c is a whitespace\n",str[i]);
        space++;
     }
     if(iscntrl(str[i])) 
     {
        printf("%c is a control character\n",str[i]);
        cntrl++;
     }
}

printf("You have %d alphabet\n",alpha);
printf("Your input has %d whitespace\n",space);
printf("Your input has %d control character\n",cntrl);

即使在我没有使用空格之后,它总是显示一个空格也控制字符,我认为这与数组大小有关。我该如何解决?

【问题讨论】:

    标签: arrays controls whitespace fgets alphabetical


    【解决方案1】:

    改变这一行:

    while(str[i])
    

    更正为:

    while(str[i++])
    

    你的完整代码:

    char str[100];    
    fgets(str,100,stdin);
    int i=0; // initialize here
    int alpha=0;    
    int space=0;
    int cntrl=0;
    while(str[i++]) // increment after each loop
    {
        if(isalpha(str[i]))
        {
            printf("%c is an alphabet\n",str[i]);
            alpha++;
        }
        if(isspace(str[i]))
        {
            printf("%c is a whitespace\n",str[i]);
            space++;
        }
        if(iscntrl(str[i])) 
        {
            printf("%c is a control character\n",str[i]);
            cntrl++;
        }
    }
    
    printf("You have %d alphabet\n",alpha);
    printf("Your input has %d whitespace\n",space);
    printf("Your input has %d control character\n",cntrl);
    

    【讨论】:

    • 什么问题?您可以尝试使用 ASCII 值来解决此问题
    • 当我在示例“asd 0 897 2*/-”中输入一个字符串时,程序应该说你的输入有 3 个空格,但它不是这个,而是 4。总是说 +1 个空格
    • 你可以试试str[i]==' ',而不是在ifisspace(str[i]) /i> 循环
    猜你喜欢
    • 1970-01-01
    • 2014-12-06
    • 1970-01-01
    • 2011-07-26
    • 2018-05-24
    • 2010-09-14
    • 2019-03-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多