p13 ,练习1-9
连续空格用一个代替
#include <stdio.h>
void main()
{
int c = getchar();
int lastc = 0;
while (c != '\n')
{
if ((c!=' ') || (lastc!=' ')) //输出字符的条件集合
putchar(c);
lastc = c;
c = getchar();
}
putchar('\n');
}
p15 ,练习1-12
每行一个单词输出
使用符号常量
#include <stdio.h>
#define IN 1
#define OUT 0
void main()
{
int c = 0;
int state = OUT;
while ((c=getchar()) != '\n')
{
if (c==' ' || c=='\t')
{
if (state == IN)
{
putchar('\n');
state = OUT;
}
}
else if (state == OUT)
{
state = IN;
putchar(c);
}
else
putchar(c);
}
putchar('\n');
}
p15~16 ,示例代码
统计各数字,空白符,其他字符数
多路判定:
if
else if
……
else
代码:
#include <stdio.h>
void main()
{
int c = 0;
int i = 0;
int nwhite = 0;
int nother = 0;
int ndigit[10];
for (i = 0; i < 10; i++)
ndigit[i] = 0;
while ((c = getchar()) != '\n')
{
if (c >= '0' && c <= '9')
ndigit[c-'0']++;
else if (c==' ' || c=='\t')
nwhite++;
else
nother++;
}
printf("digit =");
for (i = 0; i < 10; i++)
printf(" %d", ndigit[i]);
printf("\nwhite space = %d\nother = %d\n", nwhite, nother);
}