Solutions for K. N. King's C Programming: A Modern Approach, 2nd Edition, Chapter 8, Programming Project 14, produces different outputs both correct and incorrect. Examples shown below:
Reversal of sentence: you can't swallow a cage can you?
Reversal of sentence: you can't swallow a cage can you�(�?
Reversal of sentence: you can't swallow a cage can you��x�?
Reversal of sentence: you can't swallow a cage can you�Ց�?
As shown by the example input, correct output should be:
Enter a sentence: you can cage a swallow can't you?
Reversal of sentence: you can't swallow a cage can you?
My own solution and below solution (courtesy of Github user @williamgherman; slightly modified for sake of readability) both produces the different outputs.
#include <stdio.h>
int main(void)
{
char ch, terminator, sentence[100] = {0};
int i = 0, j;
printf("Enter a sentence: ");
for (i = 0; (ch = getchar()) != '\n' && i < 100; i++) {
if (ch == '.' || ch == '!' || ch == '?') {
terminator = ch;
break;
}
sentence[i] = ch;
}
printf("Reversal of sentence: ");
while (i >= 0) {
while (sentence[--i] != ' ' && i != 0)
;
j = i == 0 ? 0 : i + 1;
while (sentence[j] != ' ' && sentence[j] != '\0')
putchar(sentence[j++]);
if (i > 0)
putchar(' ');
}
printf("%c\n", terminator);
return 0;
}
Despite double checking the code, and running through the example input on paper, I've not been able to find an answer.
How come the code produces these different outputs, correct as well as incorrect? What produces the erroneous characters?