Solution for Exercise 10-1
ex1001
#include <stdio.h> void prompt(); /* function prototype */ int main() { int loop; char input[32]; loop=0; while(loop<5) { prompt(); fgets(input,31,stdin); loop=loop+1; } return(0); } /* Display prompt */ void prompt() { printf("C:\\DOS> "); }
Notes
*
Two backslashes, \\
, are used in the printf() function in Line 24. This expression is required so that a single backslash appears in the output, which is how the old MS-DOS prompt looked:
* You could modify Lines 3 and 22 so that the void keyword appears in the empty parentheses. For example, for Line 3:
And Line 22:
Whether you choose to do that is up to you. I prefer to use the word void
. If the parenthesis are empty, then it looks like I forgot something.
* The input buffer size (input[]
) and the size argument of the fgets() function are identical; fgets() won't overflow the buffer when the values are equal. I specified the value 31 (for a 32-character buffer) out of habit. Back in the old days, I was ever so cautious of buffer overflows. (I don't use fgets() to read strings in my own code because it retains the newline.)
* Code::Blocks may report an "ignored return value" warning for the fgets() statement. The function returns a pointer (covered in Chapter 18) or NULL
when a string isn't read. That's a possibility, hence the warning message. At this point in your C education, it's okay to ignore the warning.
* By the way, the main() function doesn't lack arguments. These arguments need to be specified only when they're used. Regardless, do not put void
in the main() function, as in main(void)
. This expression is incorrect and the compiler will barf.
Copyright © 1997-2024 by QPBC.
All rights reserved