我正在通过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