Article View: gnu.g++.help
Article #883Re: Operator Overloading - Result not Expected!
From: UCLA Bruin
Date: Tue, 16 Jan 1996 05:57
Date: Tue, 16 Jan 1996 05:57
47 lines
2359 bytes
2359 bytes
acinader@panix.com (Arthur Cinader) wrote:
>I am teaching myself to program with "How To Program C++" by
>Deitel & Deitel. A great book.
Maybe... But if their book is so great, why didn't their code work?
=) I recommend The C++ Primer Plus by Prata, but anyways... I can
explain the problem in their code.
>Using g++ v2.4 on BSDI I compile with:
>g++ -o fig8.3 fig8.3.C
You can just type g++ fig8.3.cpp
>// overloaded stream extraction operator
>istream &operator>>(istream &input, PhoneNumber &num)
>{
> input.ignore(); // skip (
> input.getline(num.areaCode, 4); // input area code
> input.ignore(2); // skip ) and space
> input.getline(num.exchange, 4); // input exchange
> input.ignore(); // skip dash (-)
> input.getline(num.line, 5); // input line
The problem lies here. cin.getline is supposed to be used for reading
all the characters on a line (spaces included) up until the newline
and then ignoring the newline character. As a sefety measure to
ensure you don't fill your string beyond it's bounds, you can pass an
optional integer to cin.getline to tell it when to stop the input.
With g++, cin.getline skips over the remaining characters on the line
until it reads in and ignores the newline. However, with Borland C++,
it leaves the remaining characters and newline intact. In other
words, the author probably was using Borland C++ and failed to test
his program with g++ for UNIX. The two versions have some
differences.. =) So basically with your C++ compiler it read the
first four characters and then ignored the rest of the input, hence
the result you were getting...
But all is not lost... If you use cin.get instead of cin.getline this
code will work perfectly under both compilers. The author of your
book used the wrong method for the wrong purpose.
Hope this help!
Nate
Technical Details
Message-ID:
<4dfemd$1lhs@saba.info.ucla.edu>Path:
arc1-ca.pugleaf.net!nnrp.info.ucla.edu!usenetReferences:
<4dedk3$fo2@panix.com>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!nnrp.info.ucla.edu!usenet From: bruin@ucla.edu (UCLA Bruin) Newsgroups: gnu.g++.help,comp.lang.c++ Subject: Re: Operator Overloading - Result not Expected! Date: Tue, 16 Jan 1996 05:57:38 GMT Organization: Universal Exports Message-ID: <4dfemd$1lhs@saba.info.ucla.edu> References: <4dedk3$fo2@panix.com> Reply-To: bruin@ucla.edu NNTP-Posting-Host: s110_13.resnet.ucla.edu X-Newsreader: Forte Free Agent 1.0.82