[英]Program to count the total number of vowels, consonants and words and ask for a user again for check for a letter for a string
程序計算元音、輔音、單詞的總數,並再次要求用戶檢查一個單詞在該句子中使用了多少次檢查字符串。
在這一點上,我的代碼確實檢查了元音和輔音,並且在這個程序必須要求用戶輸入一個單詞並檢查它在該句子中使用了多少次之后。
#include <stdio.h>
void main() {
char sentence[80];
int i, vowels = 0, consonants = 0, special = 0;
printf("Enter a sentence \n");
gets(sentence);
for (i = 0; sentence[i] != '\0'; i++) {
if ((sentence[i] == 'a' || sentence[i] == 'e' ||
sentence[i] == 'i' || sentence[i] == 'o' ||
sentence[i] == 'u') ||
(sentence[i] == 'A' || sentence[i] == 'E' ||
sentence[i] == 'I' || sentence[i] == 'O' ||
sentence[i] == 'U')) {
vowels = vowels + 1;
} else {
consonants = consonants + 1;
}
if (sentence[i] == '\t' ||sentence[i] == '\0' || sentence[i] == ' ') {
special = special + 1;
}
}
consonants = consonants - special;
printf("No. of vowels in %s = %d\n", sentence, vowels);
printf("No. of consonants in %s = %d\n", sentence, consonants);
}
以下是您的代碼中的一些問題:
void main()
無效:你應該寫int main()
gets(sentence);
有風險,因為超過 79 字節的輸入會導致緩沖區溢出。 此 function 是一個安全漏洞,已從 C 標准的當前版本中刪除。 您應該改用fgets()
並檢查返回值。
您只測試 TAB 和 SPACE 作為特殊字符,因此任何標點符號都將被視為輔音字母。
你不數字數
您只執行作業的第一部分。
這是使用輔助功能的修改版本:
#include <stdio.h>
#include <string.h>
int is_letter(char c) {
// Assuming ASCII
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
}
int is_vowel(char c) {
return c != '\0' && strchr("aeiouAEIOU", c) != NULL;
}
int main() {
char sentence[80];
printf("Enter a sentence \n");
if (fgets(sentence, sizeof sentence, stdin)) {
int i, vowels = 0, consonants = 0, words = 0;
char c, lastc = 0;
for (i = 0; sentence[i] != '\0'; i++) {
c = sentence[i];
if (is_letter(c)) {
if (is_vowel(c)) {
vowels = vowels + 1;
} else {
consonants = consonants + 1;
}
if (!is_letter(last)) {
words = words + 1;
}
}
last = c;
}
printf("No. of vowels = %d\n", vowels);
printf("No. of consonants = %d\n", consonants);
printf("No. of words = %d\n", words);
// implement the rest of the assignment...
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.