2013-03-19 53 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