Chinaunix首页 | 论坛 | 博客
  • 博客访问: 47332
  • 博文数量: 33
  • 博客积分: 1301
  • 博客等级: 中尉
  • 技术积分: 335
  • 用 户 组: 普通用户
  • 注册时间: 2008-08-31 21:06
文章分类
文章存档

2009年(33)

我的朋友

分类: C/C++

2009-06-20 15:56:51

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(' ');
        }
    }
}

阅读(399) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~