鱼C论坛

 找回密码
 立即注册
查看: 2374|回复: 1

[已解决]为啥输入截取两个但却截出了三个字

[复制链接]
发表于 2022-10-31 14:39:41 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
#include <stdio.h>

#define MAX 1024

int main() {
        char str1[MAX];
        char str2[MAX];

        char *target1 = str1;
        char *target2 = str2;

        char ch;
        int n;

        printf("请输入一个字符串到 str1 中:");
        fgets(str1, MAX, stdin);

        printf("请输入需要拷贝的字符个数:");
        scanf("%d", &n);

        printf("开始拷贝 str1 的内容到 str2 中...\n");
        while (n-->0) {
                ch = *target2++ = *target1++;
                if (ch == '\0') {
                        break;
                }
                if ((int)ch < 0) {
                        *target2++ = *target1++;
                        *target2++ = *target1++;
                }
        }

        *target2 = '\0';

        printf("拷贝完毕!\n");
        printf("现在,str2 中的内容是:%s\n", str2);

        return 0;
}
最佳答案
2022-10-31 15:37:12
      Linux 采用 UTF-8 编码,每个汉字占用 3 个字节
        while (n-->0) {
                ch = *target2++ = *target1++;
                if (ch == '\0') {
                        break;
                }
                if ((int)ch < 0) {
                        *target2++ = *target1++;
                        *target2++ = *target1++;
                }
        }
        但是,你的系统是 Windows,中文 Windows 采用 GBK 编码,每个汉字占用 2 个字节,所以,上面的代码必须修改为:
        while (n-->0) {
                ch = *target2++ = *target1++;
                if (ch == '\0') {
                        break;
                }
                if ((int)ch < 0) {
                        *target2++ = *target1++;
                }
        }

中文字符长度为3

中文字符长度为3

运行结果

运行结果
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2022-10-31 15:37:12 | 显示全部楼层    本楼为最佳答案   
      Linux 采用 UTF-8 编码,每个汉字占用 3 个字节
        while (n-->0) {
                ch = *target2++ = *target1++;
                if (ch == '\0') {
                        break;
                }
                if ((int)ch < 0) {
                        *target2++ = *target1++;
                        *target2++ = *target1++;
                }
        }
        但是,你的系统是 Windows,中文 Windows 采用 GBK 编码,每个汉字占用 2 个字节,所以,上面的代码必须修改为:
        while (n-->0) {
                ch = *target2++ = *target1++;
                if (ch == '\0') {
                        break;
                }
                if ((int)ch < 0) {
                        *target2++ = *target1++;
                }
        }
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-9-20 14:57

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表