C++ 计算字符的麻烦
大家好,我的任务是编写一个程序,计算一个句子中“a”字符的数量。我能使用的最复杂的代码是Dowhile for循环和switch语句。这是我目前掌握的代码。如果我把cout放在do while里面,它会说123等等,但是cout在do while循环之后甚至不会显示。我使用ascii值表来确定字母a的值。我的输出有问题,希望得到一些反馈C++ 计算字符的麻烦,c++,loops,while-loop,ascii,output,C++,Loops,While Loop,Ascii,Output,大家好,我的任务是编写一个程序,计算一个句子中“a”字符的数量。我能使用的最复杂的代码是Dowhile for循环和switch语句。这是我目前掌握的代码。如果我把cout放在do while里面,它会说123等等,但是cout在do while循环之后甚至不会显示。我使用ascii值表来确定字母a的值。我的输出有问题,希望得到一些反馈 int main() { char lettertofind; int letteramt=0; cout<<"Enter a sentence\
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;
}
intmain()
{
字符字符查找;
int-letteramt=0;
库尔特风;
做
{
cin>>字母查找;
如果(lettertofind==65 | | 97){
letteramt++;
}
}while(letterofind!='\n');
coutDo:if(lettertofind==65 | | lettertofind==97){
由于97
(或任何非0或“false”)被视为true
,因此您的情况始终被评估为true
例如,执行类似于while(97){}
的操作将创建一个无限循环(这与while(true){}
if(lettertofind==65 | | | 97)
应该读取if(lettertofind==65 | | lettofind==97)
。
您还可以在do
之前删除cin>>lettertofind;
但是这不是一个单一的问题。您的代码将只读取一个字符,因为letterofind
是用char
类型声明的。但是您请求用户键入一个完整的句子。我建议将letterofind
更改为字符串
类型,然后从用户输入中读取整行。代码c可能是这样的:
#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;
}
#包括
#包括
使用名称空间std;
int main()
{
字符串字母查找;
int-letteramt=0;
库尔特风;
getline(cin、lettertofind);
对于(int i=0;i更好地使用'a'和'a'而不是97和65),我尝试了这些步骤,但是我的代码没有输出任何东西,我不允许使用它:/i不允许使用getline命令,知道如何解决这个问题吗?