Been working on K&R exercise 1-19:
Write a program that reverses its input a line at a time.
Wrote the following program:
#include <stdio.h>
#define MAXLINE 1000
main () {
int c, x, y, z;
char ip[MAXLINE];
char ln[MAXLINE];
char rv[MAXLINE];
for (x = 0;(c=getchar()) != EOF; ++x)
ip[x] = c;
for (x = 0; ip[x] != '\0'; ++x) {
for (y = 0; ip[x] != '\n'; ++y) {
ln[y] = ip[x];
++x;
}
for (z = 0; y != -1; ++z) {
rv[z] = ln[y];
--y;
}
printf("%s\n", rv);
}
}
My problem is that this program's output is wildly inconsistent; given the same (multiple line) input, sometimes it will print each line in reverse with an added leading blank space , sometimes it will only reproduce the first line in reverse followed by blank lines, sometimes it prints garbage, and sometimes I just get an error message.
Has anybody run into this kind of volatility before without changing their code? How do I fix it?