如何将单个char拼接至string?C语言代码报错求助
解决字符拼接时的类型不兼容错误
你遇到的incompatible integer to pointer conversion error错误,核心原因是**strcat函数的参数类型不匹配**:strcat的第二个参数要求是字符串指针(const char*),但你传入的是单个char(本质是整数类型),这就触发了类型转换错误。另外你之前的两种写法还存在其他问题:
- 初始化为
string updated = ""时,这个空字符串没有足够的内存空间容纳后续字符; - 改为
char updated[text_length]时,既没有初始化数组,也依然用strcat传单个字符,所以错误不变。
正确的两种实现方式
方式一:使用CS50的string类型(动态分配内存)
CS50的string本质是char*,需要先分配足够的内存,然后逐个赋值字符,最后添加字符串终止符:
if(argc == 2 && IsDigitsOnly(argv[argc-1])) { int x = atoi(argv[argc-1]); string plaintext = get_string("plaintext: "); int text_length = strlen(plaintext); // 分配足够内存:文本长度 + 1(用于存储字符串终止符'\0') string updated = malloc(text_length + 1); if (updated == NULL) { // 内存分配失败的处理逻辑 return 1; } int idx = 0; // 记录当前要写入的位置 for (int i = 0; i < text_length; i++) { if (isalpha(plaintext[i])) { if (isupper(plaintext[i])) { // 修正凯撒密码计算:基于'A'的偏移,保证结果在A-Z范围内 int shifted = ((plaintext[i] - 'A') + x) % 26; // 处理x过大或负数的情况(如果允许负数偏移) if (shifted < 0) shifted += 26; char letter = 'A' + shifted; updated[idx++] = letter; } else { int shifted = ((plaintext[i] - 'a') + x) % 26; if (shifted < 0) shifted += 26; char letter = 'a' + shifted; updated[idx++] = letter; } } else { // 非字母字符直接保留 updated[idx++] = plaintext[i]; } } updated[idx] = '\0'; // 必须添加字符串终止符,否则printf会输出乱码 printf("ciphertext: %s\n", updated); free(updated); // 释放动态分配的内存,避免内存泄漏 }
方式二:使用固定大小的字符数组
如果不想用动态内存,可以直接声明足够大的字符数组,注意初始化和终止符:
if(argc == 2 && IsDigitsOnly(argv[argc-1])) { int x = atoi(argv[argc-1]); string plaintext = get_string("plaintext: "); int text_length = strlen(plaintext); // 声明数组时多留一个位置给终止符 char updated[text_length + 1]; memset(updated, 0, sizeof(updated)); // 初始化数组为0,避免垃圾值 int idx = 0; for (int i = 0; i < text_length; i++) { if (isalpha(plaintext[i])) { if (isupper(plaintext[i])) { int shifted = ((plaintext[i] - 'A') + x) % 26; if (shifted < 0) shifted += 26; char letter = 'A' + shifted; updated[idx++] = letter; } else { int shifted = ((plaintext[i] - 'a') + x) % 26; if (shifted < 0) shifted += 26; char letter = 'a' + shifted; updated[idx++] = letter; } } else { updated[idx++] = plaintext[i]; } } updated[idx] = '\0'; printf("ciphertext: %s\n", updated); }
额外注意点
你原来的凯撒密码计算逻辑有问题:(plaintext[i] + x) % 90会导致结果超出大写字母范围(比如'Z'加1后取模90会得到1,对应ASCII的控制字符),正确的做法是先把字符转换为0-25的偏移量,加上密钥后取模26,再转换回对应的字母。
内容的提问来源于stack exchange,提问作者matt.mcg
相关产品推荐
相关产品推荐

