| « Now is the time | The whole Myth » |
Tue, Jan 02, 2007
![[Icon]](rsc/img/chain_link.gif)
Back to K&R, and I encounter the next excercise: Write a loop to replace the trusty "Getline" function that doesn't use && or || - the "AND" and "NOT" operators
I almost didn't do this one: It basically requires you to take an elegant and simple bit of code, and replace it with something horrible. It would have been slightly better if I knew about "break" but I don't yet (by the book).
Still, I did it: Too stubborn to leave it alone. Even so, I still don't like it. Horrible bit of code.
Follow up:
{
int i, c;
for (i = c = 0; c != '\n' && (c = getchar()) != EOF && i < max-1; ++i)
string[i] = c;
string[i] = '\0';
return i;
}
That was the original bit of code. The "for" had to be replaced with a loop that didn't require && or ||, and so:
{
int i, c, cont;
i = c = cont = 0;
while (!cont)
{
if (c != '\n')
{
if ((c=getchar()) != EOF)
{
if (i < max-1)
{
string[i] =c;
++i;
}
else
cont = 1;
}
else
cont = 1;
}
else
cont = 1;
}
string[i] = '\0';
return i;
} One of the first things every CS student notices is that the more "elegant" the algorithm, the bigger and nastier it is to implement
#include <stdio.h>
int main()
{
char world[] = "Hello, world\n\0"
int i = 0;
while (world[i] != '\0')
{
putchar(world[i]);
++i;
}
return 0;
}![[Links]](http://geekblog.oneandoneis2.org/skins/112/rsc/img/chain_link.gif)
Facebook Syndication Error
03/02/12
![]()
I last listened to:
Johann Pachelbel - Canon in D major
Most recent photo:
Submersible houseboat