Reputation: 618
The following program reads a set of lines and prints the longest one. It is borrowed from 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:- Why can't we use '\n' in place of EOF and '\0' in place of '\n' ? After all, all we are doing is to denote the end of the line and end of the string,right?
Q#2:- When we know that only the last term will contain the null character. why are we using "i" as index? Why can't we directly use "limit" as the index? This should also do the job,right? Please explain.
Upvotes: 0
Views: 99
Reputation: 3830
Q1: Strings and lines are different things. A string can consist of multiple lines. For instance, it's perfectly legal for:
abc
xyz
To be a single string.
Q2: limit in this case denotes an upper bound of your loop; your copying could end before it -- just look at the other conditions controlling your loop. Besides, even if you could use limit as your index, you'd still need to keep an index of the current position.
Upvotes: 1
Reputation: 224944
Q#1:- Why can't we use '\n' in place of EOF and '\0' in place of '\n' ? After all, all we are doing is to denote the end of the line and end of the string,right?
What if your input has more than one line?
Q#2:- When we know that only the last term will contain the null character. why are we using "i" as index? Why can't we directly use "limit" as the index? This should also do the job,right? Please explain.
You need to know how far along you are in the loop as well as how many times to loop total - you could use limit
by itself, but it would make the code a lot more complicated.
Upvotes: 0