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
#include <iostream>
#include <string>
#include <fstream>
#include <cctype>
usingnamespace std;
constint 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;
}
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.