1

我目前正在用 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;
}
4

3 回答 3

3

要计算文件中的空格数:

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);

作为替代方案,您可以计算words ,而不是计算空格

std::ifstream inFile("foo.txt);
std::istream_iterator<std::string> it(inFile), end;
int numWords = std::distance(it, end);
于 2013-01-24T21:55:37.847 回答
2

这是我的做法:

std::ifstream fs("input.txt");
std::string line;
while (std::getline(fs, line)) {
    int numSpaces = std::count(line.begin(), line.end(), ' ');
}

一般来说,如果我必须为文件的每一行做一些事情,我发现 std::getline 是最不挑剔的方法。如果我需要来自那里的流运算符,我最终会从那条线中制作一个字符串流。这远不是最有效的做事方式,但我通常更关心的是把它做好并为这类事情继续生活。

于 2013-01-24T22:20:45.883 回答
1
于 2013-01-24T22:46:57.377 回答