如果在C ++中使用/ else程序,则无法掌握​​简单的布尔循环

时间:2015-09-26 05:28:34

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

我需要帮助找出C ++任务中的几个部分。我被要求编写如下程序:

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

char s[50];
int i;

. . .

i = 0;
while (s[i] != 0) { // a string is terminated with a null (0) value

. . .

i++;
}

您的程序应该使用关系运算符(例如,==<>< => =!=)来确定特定字符是字母,数字还是其他字符。你可能只#include和 可能不会使用任何其他包含文件。

该程序应具有类似于以下内容的输出:

输入一个没有空格的连续字符串(例如:aBc1234!@#$%

输入您的字符串:aBc1234!@#$%

your string has 12 total characters
3 letters
4 numerical characters
5 other characters

这是一个计算小写字母的示例程序:

// PROG07.CPP example

#include <iostream>
using namespace std;


int main()
{
char s[50];
int i;
int lowercase = 0;

//get string from the user
cout << "Enter a continuous string of characters with no blanspaces\n"
cout << "(example: aBc1234!@#$%)" << endl << endl;
cout << "Enter your string: ";
cin >> s;
cout << endl;

// loop through the string, lower case letters
// note, strings (character arrays) have an invisible
// zero value at their end
i = 0;
while (s[i] != 0) // while the character does not have ASCII code zero
{
if ((s[i] >= 'a' && s[i] <= 'z'))
lowercase++;
i++;
}

cout << "Your string has " << lowercase << " lower case letters" << endl;

// including the next line for Dev-C++:
system("pause"); // not needed for CodeBlocks

return 0;
}

到目前为止,我已经想出了这个:

#include <iostream>
using namespace std;

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

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

while (s[i] != 0) // while the character does not have ASCII code zero
{
if ((s[i] >= 'a' && s[i] <= 'z'))
    lowercase++;
    i++;
}
while (s[i] != 0)
{
if ((s[i] >= 'A' && s[i] <= 'Z'))
    uppercase++;
    i++;
}
cout << lowercase + uppercase << " letters" << endl;
i = 0;
while (s[i] != 0)
{
if ((s[i] >= '0' && s[i] <= '9'))
    numChars++;
    i++;
}

cout << numChars << " numerical characters" << endl;

return 0;
}

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:2)

你必须在每次循环之前将i重置为0:

{{1}}

答案 1 :(得分:2)

到目前为止看起来不错,只是一些事情

首先,您只需要一个while循环:

while (s[i] != 0)
{
    //All your if checks can go in here
}

然后,根据您需要的输出,您将需要4个变量:

int total, lettters, numbers, otherCharacters;

在循环开始时,添加到总计:

while (s[i] != 0)
{
    total++;
}

如果在你的while循环中检查你需要3个,一个用于字母,一个用于数字,一个用于其他字符:

if ((s[i] > 'a' && s[i] < 'z') || (s[i] > 'A' && s[i] < 'Z')) { ... }
else if (s[i] > '0' && s[i] < '9') { ... }
else { ... }

然后根据您提到的输出输出所有变量:

cout << "your string has " << total << " total characters, " << letters << " letters, " << numbers << " numerical characters, and " << otherCharacters << " characters.";