读取整行,包括来自 fstream 的空格
Read an entire line including spaces from fstream
我目前正在C++做一个小项目,目前有点困惑。我需要使用 ifstream in() 从文件中获取的一行中读取一定数量的单词。它现在的问题是它一直忽略空间。我需要计算文件中的空格量来计算单词数。无论如何,in()不忽略空格吗?
ifstream in("input.txt");
ofstream out("output.txt");
while(in.is_open() && in.good() && out.is_open())
{
in >> temp;
cout << tokencount(temp) << endl;
}
要计算文件中的空格数:
std::ifstream inFile("input.txt");
std::istreambuf_iterator<char> it (inFile), end;
int numSpaces = std::count(it, end, ' ');
要计算文件中的空格字符数,请执行以下操作:
std::ifstream inFile("input.txt");
std::istreambuf_iterator<char> it (inFile), end;
int numWS = std::count_if(it, end, (int(*)(int))std::isspace);
作为替代方案,您可以计算单词,而不是计算空格。
std::ifstream inFile("foo.txt);
std::istream_iterator<std::string> it(inFile), end;
int numWords = std::distance(it, end);
这是我
的做法:
std::ifstream fs("input.txt");
std::string line;
while (std::getline(fs, line)) {
int numSpaces = std::count(line.begin(), line.end(), ' ');
}
一般来说,如果我必须为文件的每一行做一些事情,我发现 std::getline 是最不挑剔的方式。 如果我需要那里的流运算符,我最终会用那一行制作一个字符串流。 这远非最有效的做事方式,但我通常更关心的是把它做好,并为这种事情继续生活。
您可以将
count
与istreambuf_iterator
一起使用:
ifstream fs("input.txt");
int num_spaces = count(istreambuf_iterator<unsigned char>(fs),
istreambuf_iterator<unsigned char>(),
' ');
编辑
最初我的答案使用 istream_iterator
,但是正如@Robᵩ
指出的那样,它不起作用。
istream_iterator
将循环访问流,但采用空格格式并跳过它。我上面的例子,但使用 istream_iterator
返回的结果为零,因为迭代器跳过了空格,然后我要求它计算剩余的空格。
但是,istreambuf_iterator
一次需要一个原始字符,不会跳过。
有关详细信息,请参阅 istreambuf_iterator
vs istream_iterator
。
相关文章:
- 2D数组来自文本输入,中间有空格
- 在fstream期间忽略空行
- 为字符串中每 N 个字符插入空格的函数没有按照我认为的方式工作?
- 如何在C++中读取空格分隔的输入 当我们不知道输入的数量时
- 如何在c++中使用system()来运行包含空格的python脚本
- basic_string的前导/尾部不区分空格的特征
- 移除前面有空格的前2个字符串
- 使用fstream对txt文件中的数字进行循环
- 如何将以逗号和空格分隔的整数读取到 2D 数组中?
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 无法打开 fstream C++文件,即使它与 .cpp 位于同一位置
- 如何逐行读取文件,每行中的内容都用空格分隔并将其写入新文件中
- 为什么 c++(g++) 不允许模板返回类型和函数名称之间有空格?
- 用于存储由空格分隔的字符串的 C++/C 数据结构
- 在字符串中插入空格
- 使用 fstream 在空格分隔文件中查看下一项(不仅仅是一个字符)的方法
- 仅使用 <iostream>、 <fstream> 和 <cstdlib>清除字符串中的任何多余空格
- Fstream排序-不需要一个空格字符
- 读取整行,包括来自 fstream 的空格