16.14 Answers to Chapter Questions
Answer 16-1: The problem is that you are writing an ASCII file, but you wanted a
binary file. In Unix, ASCII is the same as binary, so the program
runs fine. In MS-DOS/Windows, the end-of-line issue causes problems.
When you write a newline character (0x0a) to the file, a carriage
return (0x0D) is added to the file. (Remember that end-of-line in
MS-DOS/Windows is <carriage return><line feed>, or 0x0d,
0x0a.) Because of this editing, you get an extra carriage return
(0x0d) in the output file.
To write binary data (without output editing) you need to open the
file with the binary option:
out_file.open("test.out", std::ios::out | std::ios::binary);
Answer 16-2: The std::printf call does not check for the
correct number of parameters. The statement:
std::printf("The answer is %d\n");
tells the std::printf to print the string
"The answer is" followed by the
answer. The problem is that the parameter containing the answer was
omitted. When this happens, std::printf gets the
answer from a random location and prints garbage.
Properly written, the std::printf statement is:
std::printf("The answer is %d\n", answer);
Answer 16-3: The std::printf call does not check the type of
its parameters. You tell std::printf to print an
integer number (%d) and supply it with a
floating-point parameter (result). This mismatch
causes unexpected results, such as printing the wrong answer.
When printing a floating-point number, you need a
%f conversion. Properly written, our
std::printf statement is:
std::printf("The answer is %f\n", result);
Answer 16-4: The problem is that std::fgets gets the entire
line, including the newline character (\n). If you
have a file named sam, the program reads
sam\n and tries to look for a file by that name.
Because there is no such file, the program reports an error.
The fix is to strip the newline character from the name:
name[strlen(name) - 1] = '\0'; /* Get rid of last character */
The error message in this case is poorly designed. True, you did not
open the file, but the programmer could supply the user with more
information. Are you trying to open the file for input or output?
What is the name of the file you are trying to open? You
don't even know whether the message you are getting
is an error, a warning, or just part of the normal operation. A
better error message is:
std::fprintf(stderr, "Error: Unable to open %s for input\n", name);
Notice that this message would also help us detect the programming
error. When you typed in "sam", the
error would be:
Error: Unable to open sam
for input
This clearly shows us that you are trying to open a file with
a newline in its name.
|