Reputation: 47
Will it be too much to ask if I pray for an elucidation of the following codes from Line 7 onward? I have difficulty in comprehending how getchar() may differ from gets() or scanf() for the most parts. Why is it important to add an escape sequence, \n with it, when in my belief, the value inputting would be done in a horizontal form(as it is a 1D string)? The increment and then the immediate usage of decrement operator bewilder me too. Also, require help with the strcpy(). :| If somebody has the time, I implore guidance. Thank you!
main()
{
char st[80], ch, word[15], lngst[15];
int i, l, j;
printf("\n Enter a sentence \n ");
i = 0;
while((st[i++] = getchar()) != '\n');
i--;
st[i] = '\0';
l = strlen(st);
i = 0; j = 0;
strcpy(word," ");
strcpy(lngst," ");
while(i <= l)
{
ch = st[i];
if(ch == ' ' || ch == '\0')
{
word[j] = '\0';
if(strlen(word) > strlen(lngst))
strcpy(lngst, word);
strcpy(word," ");
j = 0;
}
else
{
word[j] = ch;
j++;
}
i++;
}
printf("\n Longest word is %s", lngst);
printf("\n Press any key to continue...");
getch();
}
Upvotes: 1
Views: 84
Reputation: 51815
I can't say why the code is written as it is (there are other input options) but I can address some of your concerns:
Why is it important to add an escape sequence, \n?
This "newline" character is returned by getchar()
when you hit the return
/enter
key (the typical 'signal' used to indicate you've done entering your line of text). Without checking for this, the getchar
function would just keep (trying to) read in more characters.
How getchar() may differ from gets() or scanf()?
It is notoriously tricky to read in text that includes spaces using the scanf
function (this SO Q/A may help), and the gets
function has been declared obsolete (because it's dangerous). One could use fgets(st, 80, stdin)
but, like I said, I can't comment on why the code is written exactly like it is.
The increment and then the immediate usage of decrement operator bewilder me too.
The expression (st[i++] = getchar())
transfers the character read into the st
array element indexed by i
and afterwards increments the value of i
, so the next call to getchar
will put its result in the next array element. But, when the \n
(newline) character has been read, i
will have been incremented, ready for the next character - but there won't be one, so we then reduce it by one after we have finished our while
loop.
Also, require help with the strcpy().
The call strcpy(dst, src)
will copy all characters in the string src
(up to and including the required nul
terminator, '\0'
) into the dst
string, replacing anything that is already there.
Feel free to ask for further clarification and/or explanation.
Upvotes: 3
Reputation: 108968
while((st[i++] = getchar()) != '\n');
has the same effect as
while (1) { // "infinite" loop
int tmp = getchar(); // get keypress
st[i] = tmp; // copy to string
i++; // update index
if (tmp == '\n') break; // exit the infinite loop after enter is processed
}
Upvotes: 1