读取整行,包括来自 fstream 的空格

Read an entire line including spaces from fstream

本文关键字:fstream 空格 包括 读取      更新时间:2023-10-16

我目前正在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 是最不挑剔的方式。 如果我需要那里的流运算符,我最终会用那一行制作一个字符串流。 这远非最有效的做事方式,但我通常更关心的是把它做好,并为这种事情继续生活。

您可以将

countistreambuf_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