首页 > 解决方案 > 在 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;
  }
}

标签: cappendcs50

解决方案


推荐阅读