1.5 字符输入/输出

标准库提供的输入/输出模型非常简单.无论文本从何处输入,输出到何处,其输入/输出都是按照字符流的方式处理.文本流是由多行字符构成的字符序列,而每行字符则由0个或多个字符组成.行末是一个换行符.标准库负责每个输入/输出流都能遵守这一模型.

标准库提供一次读/写一个字符的函数,其中最简单的是getchar和putchar函数.

每次调用时,getchar函数从文本流中读入下一个输入字符,并将其作为结果值返回.

每次调用putchar函数时将打印一个字符.

 

1.5.1 文件复制

 1 #include<stdio.h>
 2 int main()
 3 {
 4     int c;
 5     c = getchar();
 6     while (c!=EOF)
 7     {
 8         putchar(c);
 9         c = getchar();
10     }
11     return 0;
12 }

EOF(end of file) = -1

Windows中 EOF为Ctrl+z

Linux中 EOF为Ctrl+d

 

上面的字符复制程序可以精炼为:

 1 #include<stdio.h>
 2 int main()
 3 {
 4     int c;
 5     while ((c=getchar())!=EOF)
 6     {
 7         putchar(c);
 8     }
 9     return 0;
10 }


(c=getchar())!=EOF 与c=getchar()!=EOF 不同

c=getchar()!=EOF 等价于 c=(getchar()!=EOF)

该语句执行后c的值将置为0或1 

 

1.5.2 字符计数

 

 1 #include<stdio.h>
 2 int main()
 3 {
 4     long nc=0;
 5     while (getchar() != EOF)
 6     {
 7         nc++;
 8     }
 9     printf("%ld\n", nc);
10     return 0;
11 }

 

 

 1 #include<stdio.h>
 2 int main()
 3 {
 4     long nc;
 5     for (nc = 0; getchar()!=EOF; nc++)
 6     {
 7         ;
 8     }
 9     printf("%ld\n", nc);
10     return 0;
11 }

 

 1.5.3 行计数

 1 #include<stdio.h>
 2 int main()
 3 {
 4     int c, nl;
 5     nl = 0;
 6     while ((c=getchar())!=EOF)
 7     {
 8         if (c=='\n')
 9         {
10             nl++;
11         }
12     }
13     printf("%d\n", nl);
14     return 0;
15 }

 

1.5.4 单词计数

 1 #include<stdio.h>
 2 #define IN 1 //在单词内
 3 #define OUT 0 //在单词外
 4 int main()
 5 {
 6     int c;
 7     int nline, nword, nchar;
 8     int state = OUT;
 9     nline = nword = nchar = 0;
10     while ((c = getchar()) != EOF)
11     {
12         if (c == '\n')
13         {
14             nline++;
15         }
16         if (c == ' ' || c == '\n' || c == '\t')
17         {
18             state = OUT;
19         }
20         else if (state == OUT)
21         {
22             state = IN;
23             nword++;
24         }
25         nchar++;
26     }
27     printf("nline=%d\nnword=%d\nnchar=%d\n", nline, nword, nchar);
28     return 0;
29 }

 

程序执行时,每当遇到单词的第一个字符,就作为一个新的单词加以统计.

你可能感兴趣的:(1.5 字符输入/输出)