这是一个打印最长行的程序.摘自K&;R的c编程语言一书.
我的疑问是,代码的必要性是什么.
if(c == '\n'){
s[i]=c;
++i;
}
在getLine()函数中.
#include<stdio.h>
# define MAXLINE 1000 /*maximum length of the input line*/
int getLine(char s[],int line);
void copy(char from[],char to[]);
int main(){
int curr_len; //current line length
int max_len = 0; // maximum line length so far
char curr_line[MAXLINE]; // Current input line
char longest_line[MAXLINE]; // maximum line saved so far
while((curr_len = getLine(curr_line,MAXLINE))>0){
if(curr_len>max_len){
copy(curr_line,longest_line); //save the longest line
max_len = curr_len;
}
}
if(max_len>0){
printf("%s\n",longest_line);
}
return 0;
}
/* getline: read a line into s, return length*/
int getLine(char s[],int maxline){
int c,i;
for(i=0;i<maxline-1 && (c = getchar())!=EOF && c!='\n';++i){
s[i]=c;
if(c == '\n'){
s[i]=c;
++i;
}
}
s[i]='\0';
return i;
}
/* copy: copy 'from' into 'to'; assume to is big enough */
void copy(char from[],char to[]){
int i=0;
while((to[i] = from[i])!='\0'){
++i;
}
}
请解释为什么在getLine()函数中使用if语句