Exercise 1-9 (Trim blanks)
Chapter_1 Exercise_1-8 | Exercise_1-10 |
Exercise 1-9 K&R, p. 20
Exercise 1-9. Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank.
trim.c download
#include <stdio.h> // for getchar(), putchar(), EOF
// trim blanks
int main()
{
int c;
while ((c = getchar()) != EOF)
{
putchar(c);
if (c == ' ')
{
while ((c = getchar()) == ' ') // skip remaining blanks
{} // inner while ends here
if (c == EOF)
{
break; // exit outer while() or:
// putchar('\n'); return 0; // exit main()
} // else
putchar(c); // last non-blank character
}
}
}
/*
gcc trim.c -o trim
./trim // input from the keyboard
Hello! // three blanks replaced with one
Hello!
Hi, guys!
Hi, guys!
Hello, there! // tab is not replaced
Hello, there!
Hi, there! // three blanks replaced with one
Hi, there!
// Ctrl^D in Linux, Ctrl^Z+Enter in Windows (EOF)
./trim < trim.c // input from source file
./trim < trim // input from binary file
./trim < trim.c > trim2.c // output to trim2.c
gcc trim2.c -o trim2
./trim2
./trim2 < trim2.c
./trim < trim > trim2
./trim2
./trim2 < trim2.c // still working
rm trim2 trim2.c // clean
*/
Warning: You should be careful when printing the contents of a binary file in the terminal window. Some of the binary code may be interpreted as a command.
Chapter_1 Exercise_1-8 | BACK_TO_TOP | Exercise_1-10 |
Comments
Post a Comment