c++ - 从 fstream 读取整行,包括空格

标签 c++ 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);

关于c++ - 从 fstream 读取整行,包括空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14511378/

相关文章:

c++ - 如何提高 C++ 中的分支覆盖率

c++ - 编写 scons 脚本来处理许多子目录中文件的编译

c++ - 在不退出程序的情况下使用警报(3)——C++

c++ - 在 main 中捕获 ifstream 异常

c++ - 如何在 C++ 中检测空文件?

c++ - getline 并立即测试 EOF

c++ - 在 C++ 中从文本文件读取输入到数组

C++ 指针 : changing the contents without changing the address?

c++ - 从 fstream 读取输入

c# - 指向非托管数组的 double*& 的正确 P/Invoke 签名是什么?