C:从char数组打印会产生错误的字符 [英] C: Printing from char array produces erroneous characters

查看:84
本文介绍了C:从char数组打印会产生错误的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

K.N. King的 C编程:现代方法第二版的解决方案,第8章,编程项目14,产生了正确和不正确的不同输出.示例如下:

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?

我自己的解决方案和下面的解决方案(由Github用户@williamgherman提供;为了便于阅读而稍加修改)都会产生不同的输出.

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.

代码为什么会产生这些不同的输出(正确与错误)?产生错误字符的原因是什么?

推荐答案

最有可能的问题是 while 循环中用于反向打印句子的退出条件

Most likely, the problem is with the exit condition for the while loop used to print the sentence in reverse

    while (i >= 0) {
        while (sentence[--i] != ' ' && i != 0) ;
    ....

考虑代码将要打印第一个单词(i = 3)的情况:

Consider the case where the code is going to print the first word (i=3):

  • 第二个时间段将使我一直减小到0
  • 然后代码将打印单词'you'(位置0到2,包括两端)
  • 此时i = 0,第一个仍然为真
  • 第二个while会将i减至-1,并将继续将其减至-2,-3,直到找到一个空格.
  • 该代码将打印索引为-1,-2,-3的单词,并根据这些未定义的值打印字符串.

这篇关于C:从char数组打印会产生错误的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆