距离上一次更新已经过去了一个多月,对于这种拖沓,必须自我批评啊。
今天,我来继续后面内容学习的记录。
1.5 字符输入/输出
标准库提供的输入、输出按照字符流的方式处理,文本流是由多行字符组成的字符序列。getchar和putchar是标准库中的字符进行操作的两个基本函数。
1.5.1 文件复制
#include <stdio.h>
/*将输入转化到输出,版本1*/
/*读入字符,非结束符的情况下,输出读入的字符,并接收下一个字符*/
main(){
int c;
c = getchar();
while (c != EOF){
putchar(c);
c = getchar();
}
system("pause");
return 0;
}
C语言中区分结束符利用EOF(end of file,文件结束)。这里把变量c声明为int的原因是,为了让c能够包括EOF的取值范围。EOF是一个整数型,与任何char类型的值都不同。若将上述程序精练化,则可以把getchar嵌套到while循环中:
while ((c=getchar())!= EOF){
putchar(c);
}
练习1-6 验证表达式getchar()!=EOF的值是0还是1。
#include <stdio.h>
main(){
int c;
c = (getchar() != EOF);
printf("%d", c);
system("pause");
return 0;
}
验证发现,getchar()!=EOF的值是1。
练习1-7 编写一个打印EOF值的程序
#include <stdio.h>
main(){
int c;
c = EOF;
printf("%d", c);
system("pause");
return 0;
}
经过验证,EOF的值为-1。和任何char类型的值都存在不同。
1.5.2 字符计数
#include <stdio.h>
/*字符计数*/
main(){
long nc=0;
while (getchar() != EOF){
++nc;
}
printf("字符数目为:%d",nc);
system("pause");
return 0;
}
1.5.3 行计数
/*行计数*/
main(){
int c, nl;
nl = 0;
while ((c = getchar()) != EOF){
if (c == '\n')
{
++nl;
}
}
printf("行数为:%d",nl);
system("pause");
return 0;
}
练习1-8 编写一个统计空格,制表符和换行符的程序。
#include <stdio.h>
main(){
int c, ns,nt,nl;
ns = 0;//空格
nt = 0;//制表符
nl = 0;//换行符
while ((c = getchar()) != EOF){
if (c == '\n')
{
++nl;
}
if (c==' ')
{
++ns;
}
if (c=='\t')
{
++nt;
}
}
printf("空格数为:%d,制表符数为:%d,行数为:%d",ns,nt,nl);
system("pause");
return 0;
}
练习1-10 编写一个将输入复制到输出的程序,将其中的制表符替换为\t,把回退符替换为\b,把反斜杠替换为\\。这样可以将制表符和回退符以可见的方式显示出来。
#include <stdio.h>
main(){
int c;
while ((c = getch()) != EOF){
if (c=='\t')
{
putchar('\\');
putchar('t');
}
else if (c == '\b')
{
putchar('\\');
putchar('b');
}
else if (c == '\\')
{
putchar('\\');
putchar('\\');
}
else
putchar(c);
}
system("pause");
return 0;
}
这个题目涉及的是前面讲过的转义字符,制表符和反斜杠的实现都很容易。但是回退符的显示出现了问题,经查阅资料发现,getchar()函数有缓存,所以回退符无法作用,因而需要采用getch()函数来接收字符,就可以解决此问题。
1.5.4 单词计数
#include <stdio.h>
/*单词计数*/
#define IN 1 //在单词内
#define OUT 0 //在但此外
main(){
int c, nl, nw, nc, state;
state = OUT;
nl = nw = nc = 0;
while ((c = getchar()) != EOF){
++nc;
if (c == '\n')
{
++nl;
}
if (c == ' ' || c == '\t' || c == '\n')
{
state = OUT;
}
else if (state==OUT)
{
state = IN;
++nw;
}
}
printf("line:%d,word:%d,letter:%d",nl,nw,nc);
system("pause");
return 0;
}
练习1-11 你准备如何测试单词计数程序?如果程序中有某种错误,那么什么样的输入能够发现这种错误呢?
对单词的各种可能进行单一和复合测试。
练习1-12 编写一个程序,以每行一个单词的形式打印其输入。
#include <stdio.h>
/*单词计数*/
#define IN 1 //在单词内
#define OUT 0 //在但此外
main(){
int c, state;
state = OUT;
while ((c = getchar()) != EOF){
if (c == ' ' || c == '\t' || c == '\n')
{
state = OUT;
}
else if (state == OUT)
{
state = IN;
putchar('\n');
putchar(c);
}
else
putchar(c);
}
system("pause");
return 0;
}