C程序入门小程序

C程序设计语言例题代码

1-8统计空格制表符及换行符个数

#include<stdio.h>
int main()
{
    int c=0;
    int line=0;
    int tab=0;
    int space=0;
    while((c=getchar())!=EOF)//input Ctrl+D is EOF
    {
        if(c=='\n')
            line++;
        else if(c==' ')
            space++;
        else if(c=='    ')
            tab++;
    }
    printf("the number of line is %3d;\nthe number of space is %3d;\nthe number of tab is %3d;\n",line,space,tab);
    return 0;
}

1-9输入复制到输出,将连续多个空格替换为一个空格

#include<stdio.h>
int main()
{
    int c;
    int lastc='a';
    while((c=getchar())!=EOF)
    {
        if(c!=' ')
            putchar(c);
        if(c==' ')
            if(lastc!=c)
                putchar(c);
        lastc=c;

    }
    return 0;
}

1-10将制表符与回退符以可见的方式显示出来

#include<stdio.h>
int main()
{
    int c;
    while((c=getchar())!=EOF)
    {
        if(c=='\t')
            printf("\\t");
        else if(c=='\b')
            printf("\\b");//回退符用Ctrl+h输入
        else if(c=='\\')
            printf("\\\\");
        else
            putchar(c);
    }
return 0;
}

1-11统计行数、单词数及字符数

#include<stdio.h>
#define IN 1
#define OUT 0
//统计输入的行数、单词数、字符数
int main()
{
     int c;
     int line_number;
     int word_number;
     int c_number;
     int state;
     c=0;
     line_number=0;
     word_number=0;
     c_number=0;
     state=OUT;//单词的计数方式是在开始输入的时候计数,也就是由OUT变为in的时候,所以初始值要设为out;否则会少计一个单词
     while((c=getchar())!=EOF)
     {
         if(c!=' ' && c!='\t' && c!='\n')
             c_number++;
         if(c==' ' || c=='\t' || c=='\n')
             state=OUT;
         else if(state==OUT)
         {
             state=IN;
             word_number++;
         }
         if(c=='\n')
             line_number++;
     }
 printf("the line number is %d\nthe word_number is %d\nthe char number is %d\n",line_number,word_number,c_number);    
 return 0;
}

1-12以每行一个单词的形式打印输入

#include<stdio.h>
#define IN 1
#define OUT 0
int main()
{
    int c,state;
    c=0;
    state=OUT;
    while((c=getchar())!=EOF)
    {
        if(c==' ' || c=='\n' || c=='\t')
        {
            state=OUT;
            putchar('\n');
        }
        else if(state==OUT)
        {
            state=IN;
            putchar(c);
        }
        else
            putchar(c);

    }
    return 0;
}

统一说明,程序中的IN和OUT状态是为了屏蔽连续的空格换行或者制表符

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值