次のプログラムは、一連の行を読み取り、最も長い行を出力します。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:- EOF の代わりに '\n' と '\n' の代わりに '\0' を使用できないのはなぜですか? 結局のところ、行の終わりと文字列の終わりを示すだけですよね?
Q#2:- 最後の用語のみにヌル文字が含まれることがわかっている場合。なぜインデックスとして「i」を使用するのですか? 「制限」をインデックスとして直接使用できないのはなぜですか? これも仕事をするはずですよね?説明してください。