C primer plus
第8章
第1题:
#include <stdio.h>
int main(void)
{
int ch;
int i = 0;
while ((ch = getchar()) != EOF)
{
putchar(ch);
++i;
}
printf("The total input of the words is %d", i-1);
return 0;
}
第2题:
#include <stdio.h>
int main(void)
{
int ch;
int i = 0;
while ((ch = getchar()) != EOF)
{
if (i++ == 10)
{
putchar('\n'); #注:putchar需要用'\n'而不是双引号"\n".
i = 1;
}
if (ch >= 32)
{
printf("%c - %3d ", ch, ch);
}
else if (ch == '\n')
printf("\\n - \\n\n");
else if (ch == '\t')
printf("\\t - \\t\t");
else
printf("%c - ^%c", ch, ch + 64);
}
printf("Done.");
return 0;
}
第三题:
#include <stdio.h>
#include <ctype.h>
int main(void)
{
char ch;
int i = 0;
int j = 0;
int k = 0;
printf("Please enter some letters:");
while ((ch = getchar()) !=EOF)
{
if (islower(ch)) #注:当使用ctype.h头文件时可用的函数都不用表示为 ==1 或者!=1
i++;
else if (isupper(ch))
j++;
else
k++; #注:回车键也会让k加1
}
printf("The number of lower letter is %d, and upper letter is %d, %d others", i, j,k);
return 0;
}
第4题:
#include<stdio.h>
#include<ctype.h>
int main(void)
{
char ch;
int i= 0;
int j = 0;
int mark = 0;
float ave = 0;
printf("Please enter some words use space to seqrate:");
while ((ch = getchar()) != EOF)
{
if (ispunct(ch)) #注:程序用了4个if 没有用else if是因为如果用了else if 程序只会在这4条语句中4选1 比方条件满足了第4条和第4条,else if 只会运行第一条 然后重新循环,而用if就可以运行第一条之后接着运行第4条。
continue;
if (isalpha(ch))
i++;
if (isspace(ch))
{
mark = 1;
}
if (!isspace(ch) && mark == 1) #注:!isspace(ch)表示否
{
j = 1;
j++;
mark = 0;
}
}
ave = (float)i / j;
printf("Total words: %d\n", i);
printf("Total letters: %d\n", j);
printf("Average letters of words: %g\n", ave);
return 0;
}