2013-11-03 97 views
0

大家好,我一直負責編寫一個程序來計算句子中'a'字符的數量。我可以使用的最複雜的代碼是for循環和switch語句。這是迄今爲止的代碼。如果我把cout放在do中,那麼它會說123等,但是cout甚至不會在do-while循環之後顯示。我使用ascii值表來確定字母a的值。我在輸出時遇到了問題,只能欣賞一些反饋。計算字符的麻煩

int main() 
{ 
char lettertofind; 
int letteramt=0; 

cout<<"Enter a sentence\n"; 
cin>>lettertofind; 

do 
{ 
    cin>>lettertofind; 
    if(lettertofind == 65||97){ 
    letteramt++; 
    } 
}while(lettertofind != '\n'); 

cout<<"There are"<<letteramt<<" a's in that sentence"<<endl; 
return 0; 
} 
+1

使用'std :: count_if'。 – chris

+0

我不允許使用:/ –

回答

1

務必:if(lettertofind == 65|| lettertofind == 97){

由於97(或任何不爲0或「假」)被認爲是true所以你的條件總是評價是真實的。

例如做這樣while(97){}東西將創建一個無限循環(這是完全一樣while(true){}

+2

更好的使用「一」和「A」,而不是97和65 – titus

+0

香港專業教育學院嘗試了這些步驟,但我的代碼不會輸出任何東西 –

0

if(lettertofind == 65||97)應該閱讀if(lettertofind == 65|| lettertofind == 97)。 您也可以do之前刪除cin>>lettertofind;

但是,這不是一個單一的問題。您的代碼只能讀取一個字符,因爲lettertofindchar類型一起聲明,但您請求用戶鍵入整個句子,我建議將lettertofind更改爲string類型,然後從用戶輸入中讀取整行。代碼可以是這樣的:

#include<iostream> 
#include<string> 

using namespace std; 

int main() 
{ 
string lettertofind; 
int letteramt=0; 

cout<<"Enter a sentence\n"; 

// cin>>lettertofind; 
getline(cin, lettertofind); 
for(int i=0;i<lettertofind.size();i++) 
    if(lettertofind[i] == 'a' || lettertofind[i] == 'A'){ 
    letteramt++; 
    } 

cout<<"There are "<<letteramt<<" a's in that sentence"<<endl; 
return 0; 
} 
+0

香港專業教育學院現在嘗試這種但是我的代碼不會輸出任何東西 –

+0

@JamesRnepJacobs剛剛更新了答案:) –

+0

我不允許使用getline命令任何想法如何解決該問題? –