Character I/O
Goals
This lab provides practice with character-by-character input and output within the C programming language.
Reading Individual Characters
-
Program
get-3-char.creads three characters from the keyboard and prints them.-
Copy
get-3-char.cto your account, and compile it, and briefly describe what it does. -
Run the program, entering
abcon the same line (no spaces), and describe what happens. -
Run the program, entering
a b con the same line (with spaces between the letters), and describe what happens. -
Run the program, trying to enter
aon one line,bon a second line, andcon a third line. What happens? In the output, the first line appears as$a$, but the second and third lines contain a single dollar sign. Why? -
Run the program, trying to enter
abon one line,con a second line. Again, explain what happens and why. -
In the program, replace
bych1 = getchar(); ch2 = getchar(); ch3 = getchar();
Does the program behave the same (i.e., for b–e), or is something different? Why or why not?scanf ("%c", &ch1); scanf ("%c", &ch2); scanf ("%c", &ch3); -
In the previous step, replace the three
scanfstatements by the single statement:
Again, determine whether the program behaves as before or does something else, and explain what you observe.scanf ("%c%c%c", &ch1, &ch2, &ch3); - Finally, try adding a space before each %c in the scanf statement:
Again, try different types of input as before (b - e in the steps above). How does the program behave this time and why?scanf (" %c %c %c", &ch1, &ch2, &ch3);
-
Copy
Reading One Line, Character by Character with getchar
-
Program
getchar-example.creads and prints a line of characters from the keyboard. As you observed in Step 1, the single-character printing functionputchar, likegetchar, deals with a single character per call.-
Copy
getchar-example.cto your account, compile it, and briefly describe what it does. - What happens when you enter more than one letter? Why?
- What happens if you do not enter a letter, but simply
press Enter?
Recall that
getchargets a single character; blank space and newline characters are considered viable characters. -
Why do you think the line
putchar ('\n');is included?
Like
getchar,putchartakes a single character. The functionputcharprints a single character to the "standard" output stream calledstdout.
-
Copy
-
Although reading and printing one character at a time is sometimes useful by itself, a more common approach is to collect a line of characters in an array. This practice is illustrated in the
getchar-line-example.cprogram.-
Copy
getchar-line-example.cto your account, compile it, and briefly describe what it does. -
Examine the first loop. Why
does
putchar (a)precedea = getchar()? Why doesputchar ('\n')appear after the loop? What happens if you moveputchar ('\n')inside the loop? -
Examine the second loop. What is the purpose of
the
indexvariable? The loop condition involves both an assignment and a comparison. Explain how that works and why it is used. Why is the statementline[index]=0placed after the loop? -
What happens in the output if the
line
line[index]=0is deleted from after the second loop? Explain. -
Can the
linebuffer be overflowed? Amend the termination test of the while loop to fix any such problem.
-
Copy
-
Write a program that does the following:
- Declares a character array one larger than some upper size limit.
-
Reads an integer from the keyboard (likely using
scanf). This number will be used to determine the number of characters read in a later step below. -
Clears any whitespace after the number from the first line of input,
perhaps using the following expression:
while (getchar() != '\n') ; - Reads the specified number of characters from the keyboard (up to the size limit).
- Adds a null character at the end of the array.
- Prints the resulting string.
-
Modify the characters as they are entered in the previous step, so that it sets each letter to the opposite case when placing it in the string. Note that
<ctype.h>has functions that compare types and modify letter cases. For example:-
apple→APPLE -
AlPhAbEt→aLpHaBeT -
X-Ray→x-rAY
-
Programming with getchar
-
Write a program that prints a prompt for input and analyzes a line
entered by the user.
- Initially, the program should print the number of characters entered.
-
Modify your program to also print the number of uppercase and
lowercase letters in your input. (Hint: You might use
the
<ctype.h>library.) - Modify your program further to print the number of whitespace characters (e.g., tabs and spaces).
Practice with printf
-
As you have learned previously, it is important to pay close
attention to variable types, and you may have seen errors that occur
due to a type mismatch in a function. Look at the following code,
where each
printfstatement uses the wrong type for the declared variable.#include int main (void) { int x = 9, y; double s = 13.86; char * word = "computer"; char ch = word[5]; y = (int) s; printf ("\tThe value of x is %lf.\n", x); printf ("\tThe value of y is %f.\n", y); printf ("\tThe value of s is %d.\n", s); printf ("\tThe value of word is %c.\n", word); printf ("\tThe value of ch is %s.\n", ch); printf ("\tThe value of ch is %d.\n", ch); return 0; } // main - Will the code compile? Save the program to a file in your directory and check. Run the program. Do any line(s) cause the program to terminate with a segmentation fault error? Why? Think about what each of the types are and how to print those types.
-
Fix only the line(s) that prevents the code from completing, and
run the code. Explain why you get each incorrect value. How are
integers, doubles, and floats treated by each
incorrect
printfformat string? How is a character different from a string? (Hint: consider how each variable type is stored and evaluated.) -
Change the
printfformat strings so that the correct values are printed when the program is run, and check that your changes fixed the code. -
Look at the following two lines of code:
Will these two lines print the same or different output? Why?printf ("\tThe value of s is %lf.\n", s); printf ("\tThe value of s is %f.\n", s); - Make sure both lines are in your code, compile, and run. Did the output match your expectations? If not, why did the code behave this way?
-
Look closely at the following code. Will this program run as the programmer intended?
/**** * * Program to print the values of different types, with proper spacing. * It should print a as "7", b as "15.2594", and c as "something". * ****/ #include int main (void) { int a = 7; double b = 15.2594; char * c = "something"; printf ("The value of a is %d.\n", a); printf ("The value of b is %.4lf.\n", b); printf ("The value of c is %9s.\n", c); return 0; } // main - Compile and run the code. Is the output what you expected?
-
In the statement that prints the value of
b, edit the%.4lfto be%.2lf. What do you think the output will be? Compile and run the code to check. -
Now edit the statement that prints the value of
bto%.6lf. What do you think will happen? Why? Run the code to check. -
Given your previous experience, what do you think will happen if
you edit the format string for printing the value
of
cfrom%9sto%6s. What if you change it to%12s? Run the program with each of these values. Did your results match your expectations?
Practice with printf Spacing
As you may recall, when a number is placed between the '%'
character and the variable type, the printf function
allocates at least that many spaces for the information. If the
information takes that much space or more, then the data are printed
normally. However, if the information takes less space, the information
is "right-aligned" with the allocated space, with the "extra" spaces
left blank. In contrast, when a '.' character (followed by
a number) is placed between the '%' and the variable
type, only that much space is allocated after the decimal
point. For example, if the number is 48.3557, and the print statement
indicates that only one value after the decimal should be printed, the
printed result will show 48.3 as the variable inserted.
-
Modify your program from Steps 6 a, b, and c so that the code prints both the
number and the percentage of uppercase letters, lowercase letters,
and whitespace characters. Within the format string for
the
printfstatement, print all percentages to exactly two decimal places.