Hi, please help.I am trying to read values from a file by overloading the insertion stream operator.I have tried everything but it always reads the first line or always the last line.It seems that every time an object is created it starts the file from the beginning.
--------Here is my main.cpp--------------------
cout << "-- Reading in and displaying hex2 --" << endl;
HexColour hex2;
cin >> hex2;
cout << hex2;
cout << "-- Reading in and displaying hex3 --" << endl;
HexColour hex3;
cin >> hex3;
cout << hex3;
cout << "-- Reading in and displaying hex4 --" << endl;
HexColour hex4;
cin >> hex4;
cout << hex4;
cout << "-- Reading in and displaying hex5 --" << endl;
HexColour hex5;
cin >> hex5;
cout << hex5;
the problem is that i have to open the file in the overloading operator.How can i open a file and every-time a new object is created, read a new line rather than opening the file again
The operator>> reads from left hand operand istream into the right hand operand object. It does not ignore the istream and secretly fetch stuff from the dark side of the moon. That would be counter-intuitive.
cire's example opens file and stores consecutive entries into HexColour objects. Intuitively.
Your usage would not have operator, but a bool HexColour::readFromFile( const string & fileName );
If every call to a function opens the same file, then every call will read the same data. Then it is more efficient to just:
Now I am also confused.If I overload an operator, that means every time I call the cin, in my main then the overloaded operator is called instead. So my aim is call the operator through cin in main and everything is done from the implementation of the operator. Is that possible.
It should open the file read values from it.That is fine.The problem comes when I instantiate another object. Is there really a way around that
If I overload an operator, that means every time I call the cin, in my main then the overloaded operator is called instead. So my aim is call the operator through cin in main and everything is done from the implementation of the operator.
std::cin is a special file mapped to the keyboard. It is not a function that you call, it is like a global variable that operator>> uses.
And think of operators as functions with a special name, and special syntax:
1 2
cout << "Hello, World!\n"; // this is equivalent to...
operator << (cout, "Hello, World!\n");
Overloading means creating new functions with same name but different parameter types.
All the operator>> have istream as first parameter, but different second parameter type. Your HexColour version is called only when you have variable of type HexColour in the expression.