Exercise 1-8 (Count whitespace - Blanks, tabs, newlines)
Chapter_1 Exercise_1-7 count | Exercise_1-9 |
Exercise 1-8 K&R, p. 20
Exercise 1-8. Write a program to count blanks, tabs, and newlines.
white.c download
#include <stdio.h> // for getchar(), printf(), EOF
// count whitespaces
int main()
{
int c;
int blanks = 0, tabs = 0;
int lines = 1; // last line in a file may not end with '\n'
int newlines = 0;
long chars = 0;
while ((c = getchar()) != EOF)
{
chars++;
if (c == ' ') {blanks++;}
if (c == '\t') {tabs++;}
if (c == '\n') {lines++,newlines++;}
}
printf("blanks: %d\n", blanks);
printf("tabs: %d\n", tabs);
printf("lines: %d\n", lines);
printf("newlines: %d\n", newlines);
printf("chars: %ld\n", chars);
}
/*
gcc white.c -o white
./white // input from the keyboard
Hello, you!
What's up?
// Ctrl^D in Linux, Ctrl^Z+Enter for Windows (EOF)
blanks: 2
tabs: 0
lines: 3
newlines: 2
chars: 23 // 11 + 1 + 10 + 1 // 1 for newline
./white < white.c // input source file
blanks: 166
tabs: 0
lines: 51
newlines: 50
chars: 957
./white < white // input binary file
blanks: 53
tabs: 7
lines: 9
newlines: 8
chars: 16744
*/
Note: The last line in a file may not end with the newline character '\n'. Even if the line is empty, we have to count it too. Even if the file is empty, we consider it still contains one line. As such, we may say the last line in a file always ends with "EOF" (the value returned by getchar() when encountering the end of a file), not '\n' (see also copyEOF).
Chapter_1 Exercise_1-7 count | BACK_TO_TOP | Exercise_1-9 |
Comments
Post a Comment