计算新行,制表符和空格

时间:2013-03-19 21:13:42

标签: c++

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

感谢您提前协助。

2 个答案:

答案 0 :(得分:5)

您可以通过替换此

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

while ( cin.get(c) ) 

提取运算符>>遵守分隔符规则,包括空格。

istream::get没有,并逐字提取数据。

答案 1 :(得分: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 (我个人认为没问题),可以选择这样做:(作为已提供的其他解决方案的替代选项)< / p>

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