如何解决“没有运算符”!=“匹配这些操作数”?

问题描述

当我运行以下程序时,它给了我一个错误

没有运算符“!=”匹配这些操作数

错误行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;

这样。