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状态是为了屏蔽连续的空格换行或者制表符