[英]Reading number of word begin with vowels, consonant
因此,在練習中應讀取以元音,輔音和兩個類別都不適合的單詞開頭的單詞數。 到目前為止,我的代碼是:
#include <iostream>
int main()
{
using namespace std;
char a;
cout << "Enter words (q to quit)\n";
cin.get(a);
int others = 0;
int vowels =0;
int consonant =0;
while (a != 'q')
{
cin.get(a);
if(isalpha(a)) {
switch (a) {
case 'a':
case 'i':
case 'u':
case 'e':
case 'o':
vowels++;
break;
default:
consonant++;
break;
}
}
else {
others++;
}
}
cout << vowels << " words beginning with vowels\n";
cout << consonant << " words beginning with consonant\n";
cout << others << " others";
return 0;
}
但是它沒有讀單詞的開頭。 這是一個例子:
輸入單詞(q退出)
十二只真棒牛在15米高的草坪上靜靜地漫步。 q
以元音開頭的9個字
以輔音開頭的11個字
另外7個人。
問題出在哪里?
編輯:現在完成了。 如果有人感興趣
#include <iostream>
#include <cstring>
#include <cctype>
int main()
{
using namespace std;
string a;
cout << "Enter words (q to quit)\n";
int others = 0;
int vowels =0;
int consonant =0;
cin >> a;
while (a != "q")
{
cin >> a;
if(isalpha(a[0])) {
switch (a[0]) {
case 'a':
case 'i':
case 'u':
case 'e':
case 'o':
vowels++;
break;
default:
consonant++;
break;
}
}
else {
others++;
}
}
cout << vowels << " words beginning with vowels\n";
cout << consonant << " words beginning with consonant\n";
cout << others << " others";
return 0;
}
感謝所有的建議
cin.get(a)
讀取一個字符(字母)。 要讀取單詞,您可以將operator >>
與std::string
:
// make a std::string variable to hold a single word
string word;
// later read the word from the standard input
cin >> word;
您正在逐一讀取字符,直到您按“ q”並分析所有字符。 如果是我,我可能只是將所有內容連接到1個字符串中,直到“ q”,然后評估該字符串。 這可以通過在空間上分割然后在結果數組中循環所有單詞並在每個單詞的第一個字符的子字符串上進行切換來實現。
您的任務是一次讀取一個單詞,並僅考慮該單詞的第一個字母,但是您的程序在每次迭代時都讀取單個字符(使用cin.getc
)。
此外,第一個字符在while循環外讀取,並在檢查它是否不是'q'后立即丟棄。
以下代碼段更適合您的作業:
#include <iostream>
#include <string>
#include <cctype>
int main()
{
using std::cout;
int others = 0,
vowels = 0,
consonants = 0;
std::string word;
cout << "Enter words (q to quit)\n";
// read a word at a time till a single 'q'
while ( std::cin >> word && word != "q" )
{
// consider only the first letter of the word
char c = word[0];
if ( std::isalpha(c) )
{
if ( c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' ||
c == 'A' || c == 'E' || c == 'I' || c == 'O' || c == 'U' )
{
++vowels;
}
else
{
++consonants;
}
}
else
{
++others;
}
}
cout << vowels << " words beginning with vowels\n";
cout << consonants << " words beginning with consonant\n";
cout << others << " others";
return 0;
}
使用示例輸入測試程序:
The 12 awesome oxen ambled quietly across 15 meters of lawn. q
給予:
5 words beginning with vowels
4 words beginning with consonant
2 others
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.