c - 在 C 中将字符附加到空字符串的问题
问题描述
因此,我正在尝试编写将字符附加到空字符串的代码,以便从用户给出的输入构建加密字符串,但是当我尝试使用该函数时strcat()
,出现“分段错误”错误。我尝试定义一个指针 (*cipher = "") 但我仍然收到分段错误。我也尝试将 cipher 定义为一个空数组(cipher[] = "";),但我仍然得到同样的错误。有小费吗?
#include <ctype.h>
#include <cs50.h>
#include <stdio.h>
#include <string.h>
int main(int argc, string argv[])
{
string key = argv[1];
if (strlen(key) == 0)
{
printf("Please input a key");
return 1;
} else
if (strlen(key) != 26)
{
printf("Please input a 26 character key");
return 1;
} else
{
string plainText = get_string("plaintext: ");
int n = strlen(plainText);
char *cipher = "";
for (int i = 0; i< strlen(plainText); i++)
{
char letter = plainText[i];
int ASCII = (int) plainText[i];
char translation;
if (ASCII > 96 && ASCII < 123) {
int position = ASCII - 97;
int keyASCII = (int) key[position];
int toLowerCase = keyASCII + 32;
translation = (char) toLowerCase;
} else
if (ASCII > 64 && ASCII < 91) {
int position = ASCII - 65;
translation = key[position];
} else {
translation = letter;
}
strcat(cipher, &translation);
}
printf("ciphertext: %s", cipher);
return 0;
}
}
解决方案
推荐阅读
- email - 为什么在 smtp.gmail.com 上验证电子邮件地址时,有效电子邮件地址和无效电子邮件地址总是响应 250 ok?我尝试另一种方式吗?想念一些东西
- go - 如何在代理请求时在 Go Gin 中设置新的请求正文
- vba - Outlook 2010 宏以“将电子邮件另存为文件”添加不需要的换行符
- ansible - Ansible 任务用油门阻塞
- flutter - 如何打包 Flutter 库
- google-apps-script - 是否可以将下面我的 Apps 脚本中的 inputValue 转换为硬编码文本,以便注释仅显示文本?
- reactjs - RTL 中的 waitForElementToBeRemoved 错误超时
- python - Visual Studio 代码错误消息:从 bs4 导入 BeautifulSoup ModuleNotFoundError:没有名为“bs4”的模块
- c# - WebUtils.ApiCall 在 Post 之后不返回错误消息
- reactjs - 如何用玩笑调用异步模拟函数?