计算新行、制表符和空格
Counting new lines, tabs, and spaces
我正在学习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);
相关文章:
- 2D数组来自文本输入,中间有空格
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 如何在C++中读取空格分隔的输入 当我们不知道输入的数量时
- 如何在c++中使用system()来运行包含空格的python脚本
- basic_string的前导/尾部不区分空格的特征
- 如何插入 4 个空格宽的制表符并将它们删除两个空格?
- 防止控制台在通道字符(在 c++ 中)中输入空格(即空格、制表符和换行符)
- C++:按制表符拆分字符串,但包含空格
- 如何将制表符长度与Qt中的多个空格相匹配
- 标记 CString 问题与制表符空格字符
- 知道文本文件中的列数,用空格或制表符分隔
- 如何检查字符串是否包含空格/制表符/换行符(任何空白内容)?
- 如何拆分具有空格和制表符区分的文件行
- 当数据包含空格时,如何将制表符分隔文件的内容加载到C++字符串的 2D 向量中
- 如何使用 cin 读取带有空格的输入,直到到达制表符
- 试图获得一个C++switch语句来识别空格、制表符等
- 如何读取忽略制表符空格的行
- c++打印给定用户输入整数的空格或制表符
- 计算新行、制表符和空格
- 处理空格(或制表符)分隔的文件"like"和数组 - C++