C Primer Plus 第8章 字符输入/输出和输入验证
1.设计一个程序, 统计在读到文件结尾之前读取的字符数。
#include <stdio.h>
int main(void)
{
char ch;
int cnt=0;
while((ch=getchar())!=EOF)
{
cnt++;
}
printf("字符数为%d",cnt);
return 0;
}
2.编写一个程序, 在遇到 EOF 之前, 把输入作为字符流读取。 程序要打印每个输入的字符及其相应的ASCII十进制值。 注意, 在ASCII序列中, 空格字符前面的字符都是非打印字符, 要特殊处理这些字符。 如果非打印字符是换行符或制表符, 则分别打印\n或\t。 否则, 使用控制字符表示法。 例如, ASCII的1是Ctrl+A, 可显示为^A。 注意, A的ASCII值是Ctrl+A的值加上64。 其他非打印字符也有类似的关系。 除每次遇到换行符打印新的一行之外, 每行打印10对值。 (注意: 不同的操作系统其控制字符可能不同。)
#include <stdio.h>
int main(void)
{
char c;
int n_chars=0 ;
printf("Enter the text(EOF to terminate):\n");
while((c=getchar())!=EOF)
{
if(n_chars++%8==0)
{
printf("\n");
}
if(c>=32)
{
printf(" \'%c\'-%d ",c,c);
}
else if(c=='\n')
{
printf(" \'\\n\'-\\n ");
n_chars=0;
}
else if(c=='\t')
{
printf(" \'\\t\'-\\t ");
n_chars=0;
}
else
{
printf(" \'%c\'-^%c ",c,c+64);
}
}
return 0;
}
3.编写一个程序, 在遇到 EOF 之前, 把输入作为字符流读取。 该程序要报告输入中的大写字母和小写字母的个数。 假设大小写字母数值是连续的。 或者使用ctype.h库中合适的分类函数更方便。
#include <stdio.h>
#include <ctype.h>
int main(void)
{
int ch;
int upp=0,low=0;
while ((ch = getchar()) != EOF)
{
if(isupper(ch))
{
upp++;
}
if(islower(ch))
{
low++;
}
}
printf("大写字母有%d个,小写字母有%d个",upp,low);
return 0;
}
4.编写一个程序, 在遇到EOF之前, 把输入作为字符流读取。 该程序要报告平均每个单词的字母数。 不要把空白统计为单词的字母。 实际上, 标点符号也不应该统计, 但是现在暂时不同考虑这么多(如果你比较在意这点,考虑使用ctype.h系列中的ispunct()函数)。
#include <stdio.h>
#include <ctype.h>
int main(void)
{
int