gpt4 book ai didi

C: 从 char 数组打印产生错误字符

转载 作者:行者123 更新时间:2023-12-04 08:59:13 25 4
gpt4 key购买 nike

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 的退出条件上。用于反向打印句子的循环

    while (i >= 0) {
while (sentence[--i] != ' ' && i != 0) ;
....
考虑代码要打印第一个单词 (i=3) 的情况:
  • 第二个 while 将 i 一直递减到 0
  • 然后代码将打印单词“you”(位置 0 到 2,含)
  • 此时i=0,第一个while仍然为真
  • 第二个 while 将 i 递减到 -1,并将继续递减到 -2、-3,直到找到一个空格。
  • 该代码将打印索引为 -1、-2、-3 的单词,并将基于这些未定义的值打印一个字符串。
  • 关于C: 从 char 数组打印产生错误字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63635543/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com