R. Clayton (rclayton@monmouth.edu)
Tue, 18 Jul 2000 12:38:25 -0400 (EDT)
One of your colleagues wrote the following code in their dequeue assignment:
int main() {
// blah blah blah
char fileName[80], command[80];
// blah blah blah
cout <<"Please enter the file name: \t";
cin.getline(fileName, '\n');
if (fileName == '\0')
return 0;
MailBox newBox(fileName);
// blah blah blah
}
MailBox::MailBox(char * box) {
ifstream mbox(box);
// blah blah blah
if (!mbox) {
cerr << "File could not be opened: " << box << "\n";
exit(1);
}
// blah blah blah
}
What this code is supposed to do is prompt for the mailbox name and then open
the mail box. What it actually does is
$ readmbox
Please enter the file name: ../../test-mbox-1.1
File could not be opened: ../../tes
$
Can you figure out why? If you're having trouble, you might want to review
Nyhoff Section D.2.
You could argue that this problem is not directly related to using char *, but
rather to mis-using a function that uses char * parameters. Strictly speaking,
that's correct; if this particular colleague had followed the assignment's
instructions and used the char * command-line argument to get the mailbox name,
there wouldn't be a problem. However, had this particular colleague also
written the code above using strings, this problem, as well as others, would
have been eliminated.
To continue to harp on char * problems, the if statement in main() is also
interesting; can you see why? In this case, the compiler gives you a hint:
$ cxx -gall -c readmbox.cpp
cxx: Warning: readmbox.cpp, line 42: statement is unreachable
return 0;
----------------^
If you need another hint, review Nyhoff Section 2.3.
This archive was generated by hypermail 2.0b3 on Fri Aug 11 2000 - 15:25:05 EDT