如何修复 "no operator " != “匹配这些操作数”?
How to fix "no operator " != " matches these operands"?
当我运行下面的程序时,它给了我一个错误:
no operator "!=" matches these operands
错误行是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;
}
while (infile)
{
infile.get(ch);
cout << ch;
}
我是这样解决的
和
while (infile.get(ch))
cout<<ch;
这样。
istream::get()
returns 对流本身的 isteam&
引用。 istream
没有实现任何 operator!=
,更不用说接受 int
屁股输入的那个了,这就是你得到错误的原因。
然而,istream
确实实现了一个 conversion operator,您可以直接在 if
中使用它。如果流未处于错误状态,则该运算符 returns true
(或者在 C++11 之前是 non-null void*
指针)。因此,您可以将 while
语句更改为以下内容:
while (infile.get(ch))
cout << ch;
当我运行下面的程序时,它给了我一个错误:
no operator "!=" matches these operands
错误行是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;
}
while (infile)
{
infile.get(ch);
cout << ch;
}
我是这样解决的
和
while (infile.get(ch))
cout<<ch;
这样。
istream::get()
returns 对流本身的 isteam&
引用。 istream
没有实现任何 operator!=
,更不用说接受 int
屁股输入的那个了,这就是你得到错误的原因。
istream
确实实现了一个 conversion operator,您可以直接在 if
中使用它。如果流未处于错误状态,则该运算符 returns true
(或者在 C++11 之前是 non-null void*
指针)。因此,您可以将 while
语句更改为以下内容:
while (infile.get(ch))
cout << ch;