我需要一些幫助,從C++任務中找出幾個部分。我被要求編寫一個程序如下:無法掌握簡單的布爾循環if/else program in C++
編寫一個程序,接受來自鍵盤的輸入(輸入 按Enter鍵終止),並計算字母數(AZ和az),數字( 0-9)和其他字符。使用cin輸入字符串並使用以下循環結構來檢查字符串中的每個字符,並使用「if」語句和多個「else if」語句。
char s[50];
int i;
. . .
i = 0;
while (s[i] != 0) { // a string is terminated with a null (0) value
. . .
i++;
}
你的程序應該利用關係運算符(例如,== <> < => =!=),以確定一個特定的字符是否是字母,數字,或其他字符。您只可以#include和 不得使用任何其他包含文件。
程序應該有類似以下的輸出:
輸入字符的連續字符串沒有空格(例如:[email protected]#$%
)
輸入您的字符串:[email protected]#$%
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: [email protected]#$%)" << 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: [email protected]#$%)" << 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;
}
任何幫助將不勝感激。
把所有的測試在一個循環中,無需重複循環。用這種方法你遇到的問題是你在第一次循環後沒有重置'i'。 –