问题描述
没有运算符“!=”匹配这些操作数
错误行为while (infile.get(ch) != 0)
。
#include <iostream>
#include <fstream>
#include <process.h>
using namespace std;
int main(int argc,char* argv[])
{
if (argc != 2)
{
cerr << "\nFormat:otype filename";
exit(-1);
}
char ch;
ifstream infile;
infile.open(argv[1]);
if (!infile)
{
cerr << "\nCan't open " << argv[1];
exit(-1);
}
while (infile.get(ch) != 0)
cout << ch;
}
解决方法
istream::get()
返回对流本身的isteam&
引用。 istream
没有实现任何operator!=
,更不用说接受int
屁股输入的人了,这就是为什么会出现错误。
istream
确实实现了conversion operator,您可以直接在if
中使用。如果流未处于错误状态,则该运算符将返回true
(或在C ++ 11之前,返回非null的void*
指针)。因此,您可以将while
语句改为以下内容:
while (infile.get(ch))
cout << ch;
,
while (infile)
{
infile.get(ch);
cout << ch;
}
我用这种方式解决了
和
while (infile.get(ch))
cout<<ch;
这样。