我正在通過C++ Primer第5版來教自己C++。我在本書中遇到了一個問題,我不知道如何在第5章中使用他們迄今爲止提供給我的工具來解決這個問題。我有以前的編程經驗,並使用noskipws
自己解決了這個問題。我正在尋找關於如何最小限度地使用庫來解決此問題的幫助,請考慮初學者書籍的前4-5章。計算新行,製表符和空格
問題在於使用if語句讀取和計算所有元音,空格,製表符和換行符。我對這個問題的解決方案是:
// Exercise 5.9
int main()
{
char c;
int aCount = 0;
int eCount = 0;
int iCount = 0;
int oCount = 0;
int uCount = 0;
int blankCount = 0;
int newLineCount = 0;
int tabCount = 0;
while (cin >> noskipws >> c)
{
if(c == 'a' || c == 'A')
aCount++;
else if(c == 'e' || c == 'E')
eCount++;
else if(c == 'i' || c == 'I')
iCount++;
else if(c == 'o' || c == 'O')
oCount++;
else if(c == 'u' || c == 'U')
uCount++;
else if(c == ' ')
blankCount++;
else if(c == '\t')
tabCount++;
else if(c == '\n')
newLineCount++;
}
cout << "The number of a's: " << aCount << endl;
cout << "The number of e's: " << eCount << endl;
cout << "The number of i's: " << iCount << endl;
cout << "The number of o's: " << oCount << endl;
cout << "The number of u's: " << uCount << endl;
cout << "The number of blanks: " << blankCount << endl;
cout << "The number of tabs: " << tabCount << endl;
cout << "The number of new lines: " << newLineCount << endl;
return 0;
}
我能想到解決的唯一的其他方式,這是用函數getline(),然後計算的時候,它循環得到量「/ N」計數,然後通過步驟每個字符串找到'/ t'和''。
感謝您提前協助。
你的問題是什麼? – 2013-03-19 21:16:01
你這樣做對我來說似乎很好!如果您正在尋找一種縮短代碼的方法,您可以將您要搜索的字符放在數據結構中,然後檢查每個字符。但是你的實現可以完成工作。 – 2013-03-19 21:18:05
我正在尋找如何解決這個問題,而不使用像noskipws的東西。我想知道本書如何期待這個問題能夠通過迄今爲止他們給我的有限的東西來解決。 noskipws沒有提出另外10章。 – 2013-03-19 21:18:46