mcdougal@gargoyle.UChicago.EDU (Thomas F. McDougal) (11/18/87)
I hope someone can help me with this. We have no C++ wizards around here
yet, and so I have to hope that someone out there will take the time
to look this over.
I have overloaded the << operator for a particular class; the overloaded
version works fine, but now I am getting very strange behavior from cout <<
while trying to print ordinary character strings. It ignores text and "\n"
characters, and prints everything after the first four characters at the
beginning of the string.
The offending code:
cout << "Done doing something...\n";
char* w;
while (cin >> w) {
...
cout << "Could not find: "
cout << w;
cout << "\n";
}
Instead of: I get:
Done doing something... Done doing something...
Could not find: abotted tedabotted
Could not find: atmo atmo
Could not find: disciple ipledisciplenextwordnextwordne...
[etc...]
Note that it works fine until I enter the loop. Note also that after
printing a few words, scrambled and without the "could not find" but at
least on different lines, cout gives up altogether and just strings the
scrambled words onto one line.
No calls are made to the overloaded version of <<. Input is piped
from a file on the command line, like this:
a.out < inputfile
Thanks for your time, folks.
--Tom McDougal
ARPA: mcdougal@gargoyle.Uchicago.edu
UUCP: ihnp4!gargoyle!mcdougal
--
--Tom McDougal
ARPA: mcdougal@gargoyle.UChicago.edu
UUCP: ...ihnp4!gargoyle!mcdougalark@alice.UUCP (11/19/87)
In article <807@gargoyle.UChicago.EDU>, mcdougal@gargoyle.UUCP writes: > The offending code: > cout << "Done doing something...\n"; > char* w; > > while (cin >> w) { > ... > cout << "Could not find: " > cout << w; > cout << "\n"; > } w doesn't point anywhere, yet you're reading into it! You might replace char* w; by char w[200]; or some suitably large buffer. Of course, what you'd really like to be able to say is String w; while (cin >> w) { ... }; and have the String class take care of memory allocation for you. This is left as an exercise to the reader.
joemac@apple.UUCP (11/19/87)
My mailer barfed on a R to this address so here's my reply... in Article <807@gargoyle.UChicago.EDU> (Thomas F. McDougal) says: > > The offending code: > > cout << "Done doing something...\n"; > char* w; > > while (cin >> w) { > ... > cout << "Could not find: " > cout << w; > cout << "\n"; > } The problem here (besides the missing ';' after "Could not find: ") is that no store has been allocated for the characters read from cin. You have declared a char* but no real store. If you replace: char* w; with: char w[BUFSIZE]; // BUFSIZE in <stdio.h> everything is hunky-dory. Hope this helps. joe | UUCP: {decwrl,sun,voder,amdahl,well,dual,unisoft}!apple!joemac | | Internet: joemac@apple.COM |