【问题标题】:Trouble with counting characters计数字符有问题
【发布时间】:2013-11-03 23:01:47
【问题描述】:

大家好,我的任务是编写一个程序来计算句子中“a”字符的数量。我可以使用的最复杂的代码是 do while for 循环和 switch 语句。这是我到目前为止的代码。如果我将 cout 放在 do-while 中,那么它会说 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;
}

【问题讨论】:

  • 我不允许使用那个:/

标签: c++ loops while-loop ascii output


【解决方案1】:

做:if(lettertofind == 65|| lettertofind == 97){

由于97(或任何非 0 或“false”的值)被认为是 true,因此您的条件始终被评估为 true。

例如,像while(97){} 这样的操作将创建一个无限循环(它与while(true){} 完全一样

【讨论】:

  • 最好使用 'a' 和 'A' 而不是 97 和 65
  • 我尝试了这些步骤,但是我的代码没有输出任何内容
【解决方案2】:

if(lettertofind == 65||97) 应为 if(lettertofind == 65|| lettertofind == 97)。 您也可以在do 之前删除cin&gt;&gt;lettertofind;

但这不是一个单一的问题。您的代码将只读取一个字符,因为 lettertofind 声明为 char 类型。但是你要求用户输入一个完整的句子。我建议将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;
}

【讨论】:

  • 我不允许使用 getline 命令知道如何解决这个问题吗?
猜你喜欢
  • 1970-01-01
  • 2014-03-02
  • 2021-11-15
  • 2016-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-08
  • 2018-05-07
相关资源
最近更新 更多