以下程序读取一组行并打印最长的行。它是从 K&R 借来的。
#include<stdio.h>
#include<conio.h>
#define MAX 1000
int getline(char line[],int max);
void copy(char to[],char from[]);
void main()
{
int len,max=0;
char ch,char line[MAX],longest[MAX];
while((len=getline(line,MAX))>0) /* Checking to see if the string has a positive length */
{
if(len>max)
{
max=len;
copy(longest,line); /* Copying the current longer into the previous longer line */
}
}
if(max>0) /* Checking to see if the length of the string is positive */
{
printf("%s",longest);
}
}
/* Function to input the lines for comparison */
int getline(char line[],int limit)
{
int i;
char ch;
/* This for loop is used to input lines for comparison */
for(i=0;i<limit&&(ch=getchar())!=EOF&&ch!='\n';i++) /* Q#1 */
{
line[i]=ch;
}
if(ch=='\n')
{
line[i]=ch;
i++;
}
line[i]='\0'; /* Q#2 */
}
void copy(char to[],char from[])
{
int i=0;
while((to[i]=from[i])!='\0')
{
i++;
}
}
Q#1:- 为什么我们不能使用 '\n' 代替 EOF 和 '\0' 代替 '\n' ?毕竟,我们所做的只是表示行的结尾和字符串的结尾,对吧?
Q#2:- 当我们知道只有最后一个词将包含空字符时。为什么我们使用“i”作为索引?为什么不能直接用“limit”作为索引呢?这也应该做的工作,对不对?请解释。