【问题标题】:C++ while loop, using if else statements to count in an arrayC ++ while循环,使用if else语句在数组中计数
【发布时间】:2015-09-29 21:41:33
【问题描述】:

我在进行基本的 c++ 程序分配时遇到了问题,如果有任何帮助,我将不胜感激。作业如下:

编写一个接受键盘输入的程序(用输入 按 Enter 键终止)并计算字母(A-Z 和 a-z)、数字 (0-9) 和其他字符的数量。使用 cin 输入字符串,并使用以下循环结构通过“if”语句和多个“else if”语句检查字符串中的每个字符。

到目前为止,我的程序是:

#include <iostream>
using namespace std;

int main()
{
char s[50];
int i;
int numLet, numChars, otherChars = 0;

cout << "Enter a continuous string of       characters" << endl;
cout  << "(example: aBc1234!@#$%)" <<      endl;
cout  << "Enter your string: ";
cin  >> s;

i = 0;
while (s[i] != 0) // while the character does not have ASCII code zero
{
if ((s[i] >= 'a' && s[i] <= 'z') || s[i] >= 'A' && (s[i] <= 'Z'))
  {numLet++;
  }
else if (s[i] >= 48 && s[i] <= 57)
{numChars++;
    }
else if ((s[i] >= 33 && s[i] <= 4) || (s[i] >= 58  && s[i] <=64) ||  (s[i] >= 9 && s[i] <= 96) || (s[i]   >= 123 && s[i] <= 255))
  {otherChars++;
  }
  i++;
}

cout  << numLet << " letters" << endl;
cout << numChars << " numerical characters" << endl;
cout << otherChars << " other characters" << endl;

return 0;
}

字母计数给出的值有点太低,而数字计数给出的负数很大。其他字符似乎运行良好。

【问题讨论】:

  • 数字字符可以使用'0''9';注意单引号,它区分文本表示和数字(内部)表示。
  • 检查你的逻辑。对于其他字符,您需要一个if 语句还是最后一个else 语句有效?
  • 另外,使用std::stringstd::getline。如果有人输入超过 50 个字符,您的程序将开始写入字符数组之外的内容,从而导致未定义行为。否则,使用std::getline 并指定最大字符数(记得为终止字符“\0”保留空间)。
  • 另外,(s[i] &gt;= 33 &amp;&amp; s[i] &lt;= 4) 的情况不会发生。尝试一些使这个条件成立的测试用例。

标签: c++ loops if-statement while-loop


【解决方案1】:

正如另一个答案中提到的,你需要初始化你的变量,但是你在这段代码中也有一个错误:

if ((s[i] >= 'a' && s[i] <= 'z') || s[i] >= 'A' && (s[i] <= 'Z'))

括号是错误的。结果,你不计算小写字母(我认为)无论如何它应该是这样的(为了可见性而缩进):

 if (
      (s[i] >= 'a' && s[i] <= 'z') ||
      (s[i] >= 'A' && s[i] <= 'Z')
      )

您也可以使用this。因为您使用的是 c++ 而不是 c,对;)(这里的人们显然对差异感到生气)

【讨论】:

    【解决方案2】:

    您需要将每个整数设置为 0。实际上,您的代码只设置了otherChars = 0。使那行numLet = 0, numChars = 0, otherChars = 0;

    【讨论】:

    • 感谢大家的帮助,现在可以正常工作了。
    猜你喜欢
    • 2015-11-08
    • 2012-06-18
    • 2015-04-07
    • 2014-07-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 2016-10-22
    • 2016-06-04
    相关资源
    最近更新 更多