我正在学习 C++ 入门第 5 版。第 5 章中的练习说明如下:
Exercise 5.11: Write a program that counts the number of blank spaces, tabs, and newlines read.
我尝试像练习 5.11 那样使用以下代码进行操作。但是代码失败。谁能提供一些示例,说明我将如何更正代码,以便在读取输入时计数器 unsigned int cnt = 0;
将被正确迭代?
#include "stdafx.h"
#include <iostream>
int main(){
unsigned int cnt = 0;
char c1;
while (std::cin >> c1)
if (c1 == '\t' || c1 == '\n' || c1 == ' ')
++cnt;
std::cout << "The number of spaces,tabs, newlines are: " << cnt << std::endl;
system("pause");
return 0;
}
最佳答案
C++中字符分类的方法是<cctype>
中的函数或来自 <locale>
的函数: 有 std::isspace()
在这两个方面发挥作用。请注意,您只能传递正数 int
<cctype>
中函数的值,即确定是否 char c
是您要使用的空间:
if (std::isspace(static_cast<unsigned char>(c))) {
// c is a space
}
仅使用 std::isspace(c)
如果 char
会导致未定义的行为已签署并 c
是一个负值。在典型的系统上,非 ASCII 字符(或 UTF-8 编码的多个字节)使用负值。
您的原始代码中存在的问题是:
-
'/n'
不是有效的字 rune 字;你可能打算使用'\n'
. - 您省略了一些空格字符,例如
'\r'
(回车)和'\v'
(垂直空间) - 默认情况下,格式化输入运算符会跳过所有前导空格。为避免这种情况,您可以使用
std::cin >> std::noskipws;
.就个人而言,我会使用std::istreambuf_iterator<char>
获取字符。我想,这是您的主要问题。
计算空间的实用方法可能是这样的:
unsigned long spaces = std::count_if(std::istreambuf_iterator<char>(std:cin),
std::istreambuf_iterator<char>(),
[](unsigned char c){ return std::isspace(c); });
关于c++ - 检测空白字符、\t、\n 等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27610900/