您的代码存在两个问题导致倒序排序的字符串没有输出。
首先,倒序排序后的字符串存储在 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助手提供,问题来源于学员提问