No Operator "==" matches these operands.

Hello, I'm trying to play around with some code to better learn how to do another program I'm trying to write, experimenting with input files and such, but I can't figure out why this one bit of my code isn't working. When I try to compile, this is the only issue showing up. I'm using Visual Studio 2013. The error is:

error C2678: binary '==': no operator found which takes a left-hand operand of type 'std::ifstream' ( or there is no acceptable conversion )

and below that

IntelliSense: no operator "==" matches these operands
operand types are: std::ifstream == int


Here's the code I'm working with.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
  #include <iostream>
#include <string>
#include <fstream>
#include <cctype>

using namespace std;

const int MAX_NAME_LENGTH = 40;



int main()
{
	ifstream input;
	int i;
	int count = 0;
	char filename[MAX_NAME_LENGTH];
	char name[30];
	/*UNFINISHED*/

	//First communication with the user
	cout << "This program will take a basic text file of countries and their populations and sort them. \n" << "Please enter the name of your file to be sorted. \n" << "Enter File Name: ";
	cin.getline(filename, MAX_NAME_LENGTH);
	input.open(filename);
	if ( input == NULL) // THIS IS THE LINE GETTING THE ERROR
	{
		cout << "Open of file " << filename << " failed.\n";
	}

	else
	{
		input >> i;
		while (!input.eof())
		{
			count++;
			cout << i << endl;
			input >> i;
		}

		input >> name;
		i = 0;
		while (name[i] != '\0')
		{
			name[i] = tolower(name[i]);
			i++;
		}
		cout << name << endl;
		input.close();
	}


	return 0;
}

Last edited on
Instead of using the == operator, try using ifstream's member function is_open().

1
2
3
4
if (!input.is_open())
   cout << "Open of file " << filename << " failed.\n";
else
...
Thank you. I believe this has solved my problems.
Note on lines 32-38:
The operator>> returns reference to the stream.
The stream in turn can be used in condition: http://www.cplusplus.com/reference/ios/ios/operator_bool/

Therefore,
1
2
3
while ( input >> i ) {
  // This executes only if the input did succeed
}


Then we get to line 40. The previous while loop did terminate, because the stream is at EOF. By definition, the line 40 cannot possibly succeed.


One more thing:
When you have formatted input to type T and the stream contains characters that cannot be interpreted as type T value, the input operation fails and the stream has the failbit set.

If you attempt input from failed stream, the input automatically fails, even if the next characters would be of valid type. In other words the failbit has to be cleared before next input attempt.
Topic archived. No new replies allowed.