2013-11-03 98 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命令任何想法如何解决该问题? –