Lecture 6: Console I/O
Tuesday, September 20, 2011 Status: complete[Up] [Previous Lecture] [Next Lecture]
Powerpoint Slides: CL04_C_Overview.ppt, CL05_Variables.ppt
Reading Assigned: 2.3-2.4
Homework Due: Homework 2
Homework Assigned: Homework 3
Topics Covered:
- Using printf() and scanf()
Programs Shown:
- This program shows the basic use of the scanf() function using %d, %lf and %s to read in int, double and string values: scanf1.c and sample run.
-
If you forget the & in front of the variable
name, you get a segmentation fault:
scanf2.c and
sample run.
DO NOT COPY THIS PROGRAM. IT IS DELIBERATELY BUGGY! -
If you forget the l in %lf to read in a double
variable, then what the user types gets garbled. In this case, the
value is set to 0.00000 no matter what the user types. You should
use %lf for double variables and %f
for float:
scanf3.c and
sample run.
DO NOT COPY THIS PROGRAM. IT IS DELIBERATELY BUGGY! -
When you read in a string, you must reserve enough space for the string.
(You need to have space for 1 more character than the user types in. We'll
explain why later.) For example, in scanf1.c,
we reserved enough space to store 101 characters and we used %100s to
limit the user to 100 characters. In the next example, we only reserved
space for 4 characters, but still allowed the user to type in 100:
scanf4.c. If the user types in
a short string, everything is fine. However, if the user types in
a very long string, then scanf() overwrites parts of memory and
in this case, our other variables are affected:
sample run.
DO NOT COPY THIS PROGRAM. IT IS DELIBERATELY BUGGY! - Most of the errors shown above are reported by the gcc compiler, if you use the -Wall option when you compile: Wall.txt. However, even -Wall cannot detect a failure to reserve enough space for strings (the problem shown in scanf4.c).