02 November 2012

Part 8 - Character processing

Topics Covered:

Character processing using getchar() and putchar()
Counting blanks, tabs and newlines
Compressing multiple blanks into one

Watch video >>

Downloadable Files




1. Write a program cescape.c which will make the following substitutions in the input:
If the TAB character is read (\t), then output ``\t''
If the NEWLINE character is read (\n), then output ``\n''
If the BACKSPACE character is read (\b), then output ``\b''
If the BACKSLASH character is read (\\), then output ``\\''
In other words, you should replace each of the 4 characters TAB, NEWLINE, BACKSPACE and BACKSLASH in the input with the corresponding two-character escape code equivalent in the output.

2. Write a program floodnl.c that continuously outputs newlines until it is terminated. Use the following code to generate a "forever" loop:

for (;;) {
// your code here

3. The program countnl.c as written will fail if the input countains more than LONG_MAX lines. The constant LONG_MAX is defined in the standard header file limits.h. Modify the program so that it correctly handles this situation by printing the value of LONG_MAX+1 followed by a + sign, and then terminating. For example, suppose LONG_MAX is 2147483647, and suppose you have created the program floodnl.exe as described in Exercise 2. Then, running the command pipeline

floodnl | countnl 

should produce the following result:


Here is an example of how to print the number LONG_MAX+1 correctly:

#include <stdio.h>
#include <limits.h>
int main()
    printf("%lu\n", LONG_MAX + 1ul);


1. What happens if a variable is used before it is initialized? Some operating systems might even initialize these values for you in some circumstances. Should you depend on such behavior?

Note: the compiler flag -Wextra (in conjunction with -Wall) will activate warnings in the case that you blatantly try to use a variable before it is initialized. However, the compiler is not always able to detect this problem, so it should not taken as a 100% failsafe.

2. Consider the following code:

#include <stdio.h>

int main()
    int c, cmax;
    while ((c = getchar()) != EOF) {
        if (c > cmax)
            cmax = c;
    printf("%c\n", cmax);
    return 0;

The program reads characters from standard input and outputs the "maximum" character. That is, which character has the largest numeric value. What is wrong with the program? How can you fix it by adding an initialization? Is an initialization to c necessary?

No comments:

Post a Comment