C Programming (K&R) – Ch 2
Day 1
Today I just read up to Section 2.7 and did the first two exercises. They weren’t all that interesting. The chapter thus far is just a review of the types and such. Here’s my solution for Exercise 2.2. I could have used an enum but I prefer a simple flag which I called done.
#include <stdio.h>
/*
Exercise 2-2. Write a loop equivalent to the for loop above without using && or ||.
for (i=0; i < lim-1 && (c=getchar()) != '\n' && c != EOF; ++i)
str[i] = c;
*/
#define MAXLINE 1000
int main() {
char s[MAXLINE];
const int lim = MAXLINE;
int c, i, done;
for (i = 0, done = 0; done == 0; ++i) {
if (i >= lim - 1) {
done = 1;
} else if ((c = getchar()) == EOF) {
done = 1;
} else if (c == '\n') {
done = 1;
} else {
s[i] = c;
}
}
s[i-1] = '\0';
printf("%s\n", s);
return 0;
}