$
的单词。我为此使用了
while
循环。程序可以运行,但是在最后给出带有
$
符号的单词后,
print
循环内的
do
语句会再次执行
#include <stdio.h>
int main(void)
{
char word[100]; //reading a sting
printf("Enter the word That ends with $:");
int space=0;
int consonant=0;
int vowel=0;
char x;
int count;
//forcing to put $ at the end of the word
do{
count=0;
fgets(word,100,stdin);
printf("Enter the word That ends with $:");
//reading strlen
for (count ; word[count] != '\0'; count++)
{
}
}
while(word[count-2] != '$');
//connverting ti lower case to compare upper and lower case letters
for(int i=0;i<count-1;i++)
{
word[i]=tolower(word[i]);
printf("%c",word[i]);
}
//checking for vowels
for(int i=0;i<count;i++)
{
if(word[i] == 'a'||
word[i] == 'e'||
word[i] == 'i'||
word[i] == 'o'||
word[i] == 'u')
{
vowel=vowel+1;
}
//checking for spaces
else if(word[i] == ' ')
{
space=space+1;
}
//checking for consonents
//this works , why?
else if(word[i]>='a'&&
word[i]<="z")
{
consonant=consonant+1;
}
}
//output printing
printf("\n vowel=%d",vowel);
printf("\n space=%d",space);
printf("\n consonants=%d",consonant);
}
如何防止这种情况发生?
循环条件:循环条件 while(word[count-2] != '$') 在单词末尾查找 $ 字符。但是,这可能不准确,特别是当输入字符串比预期长时。您可能需要考虑使用不同的方法进行输入验证。
字符比较: 在辅音检查中,您将 word[i] 与字符串“z”进行比较,这是不正确的。您应该将它与字符“z”进行比较。
代码组织:您的代码看起来有点杂乱,尤其是在最后。确保正确构建代码以增强可读性。
#include <stdio.h>
#include <ctype.h> // Include ctype.h for tolower() function
int main(void) {
char word[100];
printf("Enter a word that ends with $: ");
int space = 0;
int consonant = 0;
int vowel = 0;
int count = 0;
do {
fgets(word, 100, stdin);
// Count the length of the string
count = 0;
while (word[count] != '\0' && word[count] != '$') {
count++;
}
// Convert all characters to lowercase
for (int i = 0; i < count; i++) {
word[i] = tolower(word[i]);
}
// Check for vowels, consonants, and spaces
for (int i = 0; i < count; i++) {
if (word[i] == 'a' || word[i] == 'e' || word[i] == 'i' || word[i] == 'o' || word[i] == 'u') {
vowel++;
} else if (word[i] == ' ') {
space++;
} else if (word[i] >= 'a' && word[i] <= 'z') { // Compare with character 'z'
consonant++;
}
}
printf("\nVowels: %d", vowel);
printf("\nSpaces: %d", space);
printf("\nConsonants: %d\n", consonant);
// Reset counts for next iteration
vowel = 0;
space = 0;
consonant = 0;
printf("\nEnter a word that ends with $: ");
} while (word[count - 1] != '$');
return 0;
}