1

我正在尝试编写一个程序来计算文件中有多少单词。

此代码正确计算字数,但为什么如果我删除iss.clear();它只会计算文件第一行中的字数?

stringstream iss;
while(getline(file, line))
{
    iss << line;
    while(getline(iss,word, ' '))
    {

        size++;
    }

    iss.clear();
}
4

1 回答 1

0

The statement while(getline(iss,word, ' ')) only gets the first line of the stringstream. Try doing this:

int pos = 0;
stringstream iss;
while(getline(file, line))
{
     iss << line;
     while(getline(iss,word, ' '))
     {
          size++;
     }

     pos += line.length();
     iss.tellg(pos);
}

The last two lines positions the read pointer at the end of the new line you added, so the next getline will actually read the next line instead of the first one over and over again.

于 2012-12-14T13:24:48.107 回答