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. How should I fix this code?
Here is a demonstrative program that shows how the while loop can look. 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
'D' : 1
'E' : 1
'H' : 1
'L' : 3
'O' : 2
'R' : 1
'W' : 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.