1.7.5
编写一条scanf语句,它需要读取两个整数,分别保存于quantity和price变量,然后再读取一个字符串,保存在一个名叫department的字符数组里。
//<Pointers on C> p16 1.7.5
#include <stdio.h>
#define LEN 20
int main(void)
{
int quantity;
int price;
char department[LEN];
scanf("%d %d %s",&quantity,&price,department);
printf("%d\n%d\n%s\n",quantity,price,department);
}
1.8.2
编写一个程序,从标准输入读取几行输入。每行输入都要打印到标准输出上,前面要加上行号。在编写这个程序时要试图让程序能够处理的输入行的长度没有限制。
要点:通过从输入中逐字符进行读取而不是逐行进行读取,可以避免行长度限制。
//<Pointers on C> p16 1.8.2
#include <stdio.h>
#include <stdlib.h>
//#define LOCAL
int main()
{
#ifdef LOCAL
freopen("data.in","r",stdin);
freopen("data.out","w",stdout);
#endif
int ch;
int line = 0;
bool at_beginning = true;
while ((ch =getchar()) != EOF)
{
if (at_beginning)
{
at_beginning = false;
line += 1;
printf("%d",line);
}
putchar(ch);
if (ch == '\n')
{
at_beginning = true;
}
}
return EXIT_SUCCESS;
}
1.8.3
编写一个程序,从标准输入读取一些字符,并把它们写到标准输出上。它同时应该计算checksum值,并写在字符的后面。
//<Pointers on C> p16 1.8.3
#include <stdio.h>
//#define LOCAL
int main()
{
#ifdef LOCAL
freopen("data.in","r",stdin);
freopen("data.out","w",stdout);
#endif
int ch;
char checksum = -1;
while ((ch = getchar()) != EOF && ch != '\n')
{
putchar(ch);
checksum += ch;
}
printf("\n%d\n",checksum+'\n');
return 0;
}
1.8.4
编写一个程序,一行行地读取输入行,直至到达文件尾。算出每行输入行的长度,然后把最长的那行打印出来。可以假定输入行均不超过1000个字符。
//<Pointers on C> p17 1.8.4
#include <stdio.h>
#include <string.h>
#define MAX 1000
#define LOCAL
int main()
{
#ifdef LOCAL
freopen("data.in","r",stdin);
freopen("data.out","w",stdout);
#endif
char input[MAX];
char output[MAX];
memset(output,0,MAX);
int len = 0;
int len_max = 0;
while ((gets(input) != NULL))
{
len = strlen(input);
if (len > len_max)
{
len_max = len;
strncpy(output,input,len);
}
}
//puts(output);
printf("%s",output);
return 0;
}
未解决的问题:
标准输入中的结束问题。以1.8.3为例,在第15行代码中,如果不要&&后面的条件,则不能检测到一行的结束,而采用freopen()的方式就可以实现。
待解。