【发布时间】: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::string和std::getline。如果有人输入超过 50 个字符,您的程序将开始写入字符数组之外的内容,从而导致未定义行为。否则,使用std::getline并指定最大字符数(记得为终止字符“\0”保留空间)。 -
另外,
(s[i] >= 33 && s[i] <= 4)的情况不会发生。尝试一些使这个条件成立的测试用例。
标签: c++ loops if-statement while-loop