简体   繁体   English

我有一个关于 c 使用 While 编程无限循环的问题

[英]I have a question about c programming infinite loop using While

int main() {
    int count[26]={0};
    char input;
    int i;
    while(1){
        scanf("%c", &input);
        if(input>='a'&&input<='z') count[input-'a']++;
        else if(input>='A'&&input<='Z') count[input-'A']++;
        else break;
    }
    for (i=0; i<26; i++) {
        if(count[i]!=0) {
            printf("%c : %d\n", 'A'+i, count[i]);
        }
    }
    return 0;
}

I want this code to stop when a value other than A~Z or a~z is entered.当输入 A~Z 或 a~z 以外的值时,我希望此代码停止。 How should I fix this code?我应该如何修复此代码?

Here is a demonstrative program that shows how the while loop can look.这是一个演示程序,展示了 while 循环的外观。 I considered the space character ' ' as a valid character but it is not counted.我将空格字符 ' ' 视为有效字符,但未计算在内。

#include <stdio.h>
#include <ctype.h>

int main(void) 
{
    unsigned int count['Z' - 'A' + 1] = { 0 };
    const size_t N = sizeof( count ) / sizeof( *count );
    char c;

    while ( scanf( "%c", &c ) == 1 && 
            ( (  'A' <= ( c = toupper(( unsigned char ) c ) ) && c <= 'Z' ) || c == ' ' ) )
    {
        if ( c != ' ' ) ++count[c - 'A'];
    }

    for ( size_t i = 0; i < N; i++ )
    {
        if ( count[i] )
        {
            printf( "'%c' : %u\n", ( char )( 'A' + i ), count[i] );
        }
    }

    return 0;
}

If to enter this sentence如果输入这句话

Hello World

then the program output will be那么程序 output 将是

'D' : 1
'E' : 1
'H' : 1
'L' : 3
'O' : 2
'R' : 1
'W' : 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM