trouble with >> overload

J

Jaime Ashander

Hello,
I've overloaded the istream operator >> to output the private
data members of my class Word, i'm using the operator go get
data from an input file with something like
//--snip--
#include <iostream>
#include <fstream>
#include <cstdlib>
int main(int argc, char* argv[]) {
ifstream in(arcv[1]);
//...
word W;
while(!in.eof()) {
in >> W;
cout << W;
}
//--snip--
below is the class and overload declarations, the problem is that
if I attempt to read in a file with 16 zeroes in it, the above code
will print 17 zeroes to counsole.
I suspected after looking thru with a debugger, that the blank char
at the end of the file is being read into istream and instantiating
a word object with the default constructor(no args). But when I change
this constructor to
this->wr = 0xfff;
the 17th digit does not become 0xfff or its decimal equvalent, it is
still zero.

Any Ideas as to what is happening here?

class word {
private:
unsigned long wr;
public:
word(void) {
this->wr = 0;
}
unsigned long value(void) {
return (this->wr);
}
void set(char* s_wr) {
this->wr = strtoul(s_wr,'\0',16);
}
};
extern istream &operator >> (istream &in, word &wr);
extern ostream &operator << (ostream &out, word &wr);
//////////////////////////////
istream &operator >>(istream &in, word &wr) {
char* line;
line = new char[33];
in >> ws;
in >>line;
if (in.bad()) return(in);
wr.set(line);
delete[] line;
return (in);
}

ostream &operator <<(ostream &out, word &wr) {
out << hex << wr.value()<<endl;
return(out);
}
/////////////////////////////


THanks,
Jaime
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,228
Latest member
MikeMichal

Latest Threads

Top