Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

please do help me guys

yogiyogi indiaMember Posts: 1

"please give me quite an explaination so that i can understand my query properly...thank you :) " i am a beginner and was learning to code using k&r's c programming book. now there is this example of "a program to input set of text lines and print the longest" i am giving you the whole code......

#include<stdio.h>
#define MAXLINE 1000

int getline(char line[], int maxline);
void copy(char to[], char from[]);

int main()
{
int len;
int max;
char line[MAXLINE];
char longest[MAXLINE];
max=0;

while((len=getline(line,MAXLINE))>0)
if(len>max)
{
max=len;
copy(longest,line);
}
if(max>0)
printf("%s",longest);
return 0;
}

int getline(char s[], int lim)
{
int c,i;
for(i=0;i<lim-1&&(c=getchar())!=EOF&&c!='\n';i++)
s[i]=c;
if(c=='\n')
{
s[i]='\n';
i++;
}
s[i]='\0';
return i;
}

void copy(char to[], char from[])
{
int i;
i=0;
while((to[i]=from[i])!='\0')
i++;
}

now tell me.... in getline function.... in the statement

for(i=0;i<lim-1&&(c=getchar())!=EOF&&c!='\n';i++)

why do we use " c!='\n' "

and what is the meaning of code after this for statement

i.e.

 s[i]=c;
 if(c=='\n)
 {
 s[i]=c;
 i++;
 }
 s[i]='\0'

why have we used s[i]='\0' in this

and i++; statement in if(c=='\n') condition

Tagged:

Answers

  • ajitreenajitreen Member Posts: 14

    Dear Yogi

    Q1) why do we use " c!='\n' "

    Ans c!='\n' translates to [c] [not equal to ] [Enter key pressed]

          Which means that continue to input the  current line till you     
          press the Enter key                  
    

    Q2) Meaning of the code after ....
    Ans s[i]=c; // since enter key is not pressed this character gets
    // to be in the string s as the ith character
    if(c=='\n) // if c == enter key
    {
    s[i]=c; // enter key is pressed and is the ith character of
    //string s

        i++;         // one more character added to string s[]
          }
           s[i]='\0'          // to mark the end of input '\0' to tell c no more
                             // characters after this the function len() will 
                                 // stop counting when it sees '\0'.
    

    I hope these lines illustrative enough and answer what you are looking forward to.

    The thumb rule to follow when you get stuck is to GO BACK TO THE BASICS not to feel shy as we all are learning.

Sign In or Register to comment.