C++EOF结束输出与get()函数的相关问题

#include <iostream>
int main()
{
using namespace std;
char ch;
int count = 0;

cout << "Enter characters; enter # to quit:\n";
cin.get(ch); // use the cin.get(ch) function
while (ch != '#')
{
cout << ch;
++count;
cin.get(ch); // use it again
}
cout << endl << count << " characters read\n";
// get rid of rest of line
// while (cin.get() != '\n')
// ;
//cin.get();
return 0;
}
这里我可以使用ch判断是否等于对应的字符,为什么不能用ch判断是否到达EOF
// textin3.cpp -- reading chars to end of file
#include <iostream>
int main()
{
using namespace std;
char ch;
int count = 0;
cin.get(ch); // attempt to read a char
while (cin !=EOF) // test for EOF 输入回车加ctrl时会一直输出。
{
cout << ch; // echo character
++count;
cin.get(ch); // attempt to read another char
}
cout << endl << count << " characters read\n";
return 0;
}
可是却可以通过函数返回值的方式判断

第1个回答  2018-07-24
或许是我的回答并没那么清晰,导致你无法理解,不过,别人花了时间逐行去看你的程序去分析,起码应该礼貌的回复,如果我说的不全面或者错了,可以指出。我再补充一下:
问题1cin.get(char ch)当遇到EOF的输入时候,ch并不会接收EOF,cin对象同时会对自身标记错误,后续及时再使用cin.get(char ch),由于有错误标记,他不会再工作,所以的循环会一直执行。不过可以用cin.clear()来恢复它。一般的做法是用返回值
while (cin.get(ch)!=0)
问题2while (cin !=EOF)程序意图不明,编程是严谨的事情,程序不明的语句是没法分析的。
相似回答