我很难理解为什么 while (cin.get(Ch))
没有看到 EOF
.我读入了一个包含 3 个单词的文本文件,当我调试时,我的 WordCount 为 3(正是我所希望的)。然后它回到 while 循环并卡住。 Ch
然后没有值(value)。我以为在换行之后它会读到 EOF
并爆发。我不允许使用 <fstream>
,我必须在 DOS 中使用重定向。非常感谢。
#include <iostream>
using namespace std;
int main()
{
char Ch = ' ';
int WordCount = 0;
int LetterCount = 0;
cout << "(Reading file...)" << endl;
while (cin.get(Ch))
{
if ((Ch == '\n') || (Ch == ' '))
{
++WordCount;
LetterCount = 0;
}
else
++LetterCount;
}
cout << "Number of words => " << WordCount << endl;
return 0;
}
最佳答案
while (cin >> Ch)
{ // we get in here if, and only if, the >> was successful
if ((Ch == '\n') || (Ch == ' '))
{
++WordCount;
LetterCount = 0;
}
else
++LetterCount;
}
这是安全且通用的重写代码的方法,只需进行最少的更改。
(您的代码很不寻常,试图扫描所有字符并计算空格和换行符的数量。我将对一个稍微不同的问题给出更笼统的答案 - 如何读入所有单词。)
如果 if(stream)
,检查流是否完成的最安全方法。当心 if(stream.good())
- 它并不总是按预期工作,有时会过早退出。最后一个 >>>
变成一个 char
不会把我们带到 EOF,但是最后一个 >>>
变成一个 int
或 string
将 带我们到 EOF。这种不一致可能会造成混淆。因此,使用 good()
或任何其他测试 EOF 的测试都是不正确的。
string word;
while(cin >> word) {
++word_count;
}
if(cin)
和 if(cin.good())
之间有一个重要的区别。前者是operator bool
conversion .通常,在这种情况下,您想测试:
"did the last extraction operation succeed or fail?"
这不与:
"are we now at EOF?"
在最后一个单词被cin >> word
读取后,该字符串位于EOF。但是 word
仍然有效并且包含最后一个单词。
TLDR:eof
位并不重要。 错误
位是。这告诉我们最后一次提取失败。
关于c++ - 简单的 C++ 不读取 EOF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21389484/