【发布时间】:2020-12-17 11:47:57
【问题描述】:
K. N. King 的 C 编程解决方案:一种现代方法,第 2 版,第 8 章,编程项目 14,会产生正确和不正确的不同输出。示例如下:
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�Ց�?
如示例输入所示,正确的输出应该是:
Enter a sentence: you can cage a swallow can't you?
Reversal of sentence: you can't swallow a cage can you?
我自己的解决方案和下面的解决方案(由 Github 用户 @williamgherman 提供;为便于阅读稍作修改)都产生不同的输出。
#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;
}
尽管仔细检查了代码,并通过纸上的示例输入运行,我还是找不到答案。
代码为什么会产生这些不同的输出,正确的和不正确的?是什么产生了错误字符?
【问题讨论】:
-
在
while (i >= 0)循环内,i在某些时候变为负数。您需要对此进行调试。这是开始学习如何使用调试器的绝佳机会。 -
while循环的最后一次迭代有i == 0。所以sentence[--i]访问数组外的sentence[-1]。 -
@Jabberwocky -- 你能推荐一个调试器吗?我正在使用 GCC 编译我的代码。
-
使用 gdb。如果您使用一些 IDE(我强烈推荐),很可能会包含调试器。
标签: c loops char reverse c-strings