Problem Statement:
Exercise 1-8: Write a program to count blanks, tabs and newlines.Solution:
Blank is ' ', tab is '\t' and newline is '\n'.Strategy
- Lets take one character time as the input using getchar() in a loop.
- Each character is compared against ' ', '\t', '\n'.
- If it matches then appropriate counters are incremented.
- Loop will end when the character input is EOF.
#include <stdio.h> int main() { int c; int count_blank = 0; int count_tab = 0; int count_newline = 0;
while((c = getchar()) != EOF) { if(c == ' ') { count_blank++; }else if(c == '\t'){ count_tab++; }else if(c == '\n'){ count_newline++; } } printf("Total Blank is %d\n", count_blank); printf("Total Tab is %d\n", count_tab); printf("Total New line is %d\n", count_newline); return 0; }
Output
Input from keyboard
$./e_1_08.out This is very long line. This is yet another line. Total Blank is 8 Total Tab is 2 Total New line is 2
Using Pipe
$ cat text This is very long line. This is yet another line. $ cat text | ./e_1_08.out Total Blank is 9 Total Tab is 3 Total New line is 2
Using file redirection
$ ./e_1_08.out < text Total Blank is 9 Total Tab is 3 Total New line is 2
Links
Next Article - K&R Exercise 1.9 Replace multiple blank with single blankPrevious Article - K&R Exercise 1.7 Value of EOF
All Article - K & R Answers
No comments :
Post a Comment