Exercise 1-8. Write a program to count blanks, tabs, and newlines.
#include<stdio.h>
int main(){ int c, n1, n2, n3; n1 = 0; n2 = 0; n3 = 0; while((c = getchar()) != EOF){ if(c == ' ') n1 ++; else if(c == '\t') n2 ++; else if(c == '\n') n3++; } printf("space: %d, tab: %d, newline: %d\n", n1, n2, n3); }
|
Exercise 1-9. Write a program to copy its input to its output, replacing each string of one ormore blanks by a single blank.
version1:
#include<stdio.h>
int main(){ int c; while((c = getchar()) != EOF){ putchar(c); if(c == ' '){ while((c = getchar()) == ' ') ; ungetc(c, stdin); } } }
|
version2:
#include<stdio.h>
int main(){ int c;
c = getchar(); while(c != EOF){ putchar(c); if(c == ' '){ while((c = getchar()) == ' ') ; continue; } c = getchar(); } }
|
version 3:
#include<stdio.h>
int main(){ int c, state; state = 1; while((c = getchar()) != EOF){ if(c != ' '){ state = 1; putchar(c); } else if(state == 1){ state = 0; putchar(' '); } } }
|
阅读(416) | 评论(0) | 转发(0) |