C语言字符串插入程序输出异常:字符丢失问题的排查与修复
问题分析与修复
你的程序丢失主字符串pos位置字符的原因,并非j的后置自增操作,而是循环逻辑错误:当i == pos时,程序仅插入了待添加的字符串,却跳过了主字符串中text[i]这个字符(也就是示例中的'm'),直接让i自增,导致该字符没有被复制到结果数组ins_text中。
修复方法
去掉else分支,当i == pos时,先插入待添加的字符串,之后依然要将当前text[i]复制到ins_text中,而不是跳过它。
修复后的完整代码:
/*write a program to insert a string into main string*/ #include <stdio.h> #include <string.h> int main() { char text[100], str[20], ins_text[100]; int i = 0, j = 0, k = 0, pos; printf("enter main text: "); // 替换不安全的gets,用fgets读取并去除换行符 fgets(text, sizeof(text), stdin); text[strcspn(text, "\n")] = '\0'; printf("enter string to be inserted: "); fgets(str, sizeof(str), stdin); str[strcspn(str, "\n")] = '\0'; printf("enter the position to be inserted: "); scanf("%d", &pos); while (text[i] != '\0') { if (i == pos) { // 插入待添加的字符串 while (str[k] != '\0') { ins_text[j] = str[k]; j++; k++; } } // 无论是否触发插入,都复制当前主字符串的字符 ins_text[j] = text[i]; j++; i++; } ins_text[j] = '\0'; printf("\n the new string is: "); puts(ins_text); return 0; }
改动说明
- 核心逻辑修复:移除else分支,确保
i == pos时,插入完待添加字符串后,依然会将主字符串当前位置的字符复制到结果数组,避免丢失。 - 安全性优化:将存在缓冲区溢出风险的
gets()替换为fgets(),并通过strcspn()自动去除读取时带入的换行符,避免干扰字符串内容。
测试示例运行结果:
$ ./a.exe enter main text: newsman enter string to be inserted: paper enter the position to be inserted: 4 the new string is: newspaper
内容的提问来源于stack exchange,提问作者prit
相关产品推荐
相关产品推荐

