ZBLOG

#include #define MAXSIZE 100 void inverted_order(char *str_input, int length, char *str_output); int main() { char str_input[MAXSIZE]; char str_output[MAXSIZE]; int count = 0; // 在主函数输入一个任意长度的字符 printf("请输入一个任意长度...

您的代码存在两个问题导致倒序排序的字符串没有输出。

首先,倒序排序后的字符串存储在 str_output 数组中,但在函数最后打印输出时,您使用了 printf 函数并传递给它 str_output 字符指针。然而,此时 str_output 已经指向了数组结尾,而不是字符串的开头,因此会输出错误的结果。解决方法是在打印之前将 str_output 指针重新指向字符串开头。

其次,在主函数中调用 inverted_order 函数时,传递给它的参数类型不正确。应该将 count + 1 作为长度传递给函数,并确保在函数内部处理字符串末尾的换行符。修改这部分代码可以解决这个问题。

下面是修正后的代码:

#include <stdio.h>
#define MAXSIZE 100

void inverted_order(char *str_input, int length, char *str_output);

int main()
{
    char str_input[MAXSIZE];
    char str_output[MAXSIZE];
    int count = 0;

    // 在主函数输入一个任意长度的字符
    printf("请输入一个任意长度的字符:");
    fgets(str_input, sizeof(str_input), stdin); //使用fget函数输入字符串

    while (str_input[count] != '\0' && str_input[count] != '\n')
        count++;

    printf("输入的字符串为:%s", str_input);

    inverted_order(str_input ,count + 1, str_output);

    return 0;
}

void inverted_order(char *str_input, int length, char *str_output)
{
    char *p =  str_input + length - 2; // 去除换行符

    while (length > 1)
    {
        *str_output = *p;
        str_output++;
        length--;
        p--;
    }
    
    *str_output = '\0'; // 添加字符串结尾标志
    printf("倒序排序的字符串为:%s", str_output);
}

修改后的代码会正确输出倒序排序后的字符串。希望对您有所帮助!


内容由零声教学AI助手提供,问题来源于学员提问

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:http://sdn.0voice.com/?id=2097

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?