计算新行、制表符和空格

Counting new lines, tabs, and spaces

本文关键字:空格 制表符 新行 计算      更新时间:2023-10-16

我正在学习c++入门第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'和' '。

事先感谢您的协助

您可以通过替换

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

while ( cin.get(c) ) 

提取操作符>>遵循分隔符规则,包括空格。

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

你的代码运行得很好:

输入:

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);