Hello all,
Here I intend to reverse a line of text ending in a newline, but only the individual words will be reversed, not every character. For example, "This is just a test." would output ".test a just is This". The code as stands prints a space for every character in the word, as I cannot think of a way to recapture the previously read characters.
I think my professor is a sadist... we have to process the input one character at a time, recursively and cannot use any extraneous structures such as an array.
<disclaimer> This is just for bonus, and I intend to let him know that I received outside help on it. The actual assignment was to reverse a string of text, one character at a time, recursively.</disclaimer>
#include <stdio.h>
int reverseWords(int);
int main() {
char ch;
while ( (ch = getc(stdin)) != EOF ) {
ungetc(ch,stdin);
reverseWords(1);
putc('\n', stdout);
}
return 0;
}
int reverseWords(int count) {
char ch;
ch = getc(stdin);
if (ch == '\n') return;
else if (ch == ' ') {
for (count; count > 0; count--) {
putc(ch, stdout);
}
}
reverseWords(count+1);
}
Just for kicks, here is the (working) code to reverse a single line of text, preserving the newline at the end.
#include <stdio.h>
void reverseLine(void);
int main() {
char ch;
while ( (ch = getc(stdin)) != EOF ) {
ungetc(ch,stdin);
reverseLine();
putc('\n', stdout);
}
return 0;
}
void reverseLine(void) {
char ch;
if ( (ch = getc(stdin)) == '\n') return;
reverseLine();
putc(ch, stdout);
}