2013-03-19 50 views
0

我正在通過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'和''。

感謝您提前協助。

+5

你的問題是什麼? – 2013-03-19 21:16:01

+0

你這樣做對我來說似乎很好!如果您正在尋找一種縮短代碼的方法,您可以將您要搜索的字符放在數據結構中,然後檢查每個字符。但是你的實現可以完成工作。 – 2013-03-19 21:18:05

+1

我正在尋找如何解決這個問題,而不使用像noskipws的東西。我想知道本書如何期待這個問題能夠通過迄今爲止他們給我的有限的東西來解決。 noskipws沒有提出另外10章。 – 2013-03-19 21:18:46

回答

5

您可以通過替換該

while (cin >> noskipws >> c) 
避免

while (cin.get(c)) 

提取操作者>>觀察定界符規則,包括空格。

istream::get不,並提取數據逐字。

+0

這是行得通的,但我唯一的問題就是get也沒有在書中提到另外8個章節,只有getline()已經被提到。我開始認爲這個問題的解決方案是由作者忽略的,因爲像get和noskipws這樣的工具沒有被引入。 – 2013-03-19 21:27:56

+0

@MK'getline()'有什麼問題?當然,它會刪除換行符,但是您可以測試流的'eof()',如果沒有設置,換行符就在那裏。 – Angew 2013-03-19 21:30:31

+0

@MK也許吧。你提到的「唯一的另一種方式」也是可靠的。 – 2013-03-19 21:33:02

0

你的代碼工作perfectly fine

輸入:

This is a test or something 
New line 
12345 
Test 21 

輸出:

The number of a's: 1 
The number of e's: 5 
The number of i's: 4 
The number of o's: 2 
The number of u's: 0 
The number of blanks: 7 
The number of tabs: 0 
The number of new lines: 3 

我建議你檢查出std::tolower()函數,用於測試上和小寫字符在同一時間。 此外,要檢查任何類型的字母,請查看std::isalpha()std::isdigit(),std::isspace()和類似的函數。

此外,您可以使函數不依賴於std :: cin,而是使用std :: cin來獲取一個字符串,並將該字符串傳遞給函數,這樣函數可以用於任何字符串,不只是std :: cin輸入。

爲了避免使用noskipws(我個人認爲是好的),一種選擇是要做到這一點:(作爲替代選項,已經提供的其他解決方案)

std::string str; 
//Continue grabbing text up until the first '#' is entered. 
std::getline(cin, str, '#'); 
//Pass the string into your own custom function, to keep your function detached from the input. 
countCharacters(str); 

(見here for an example

+0

謝謝,我會檢查出來的。 – 2013-03-19 21:32:01