首页 > 解决方案 > C 中的局部作用域

问题描述

我在C中有这样的东西:

string getCipherText(string text, int key) {
    string cipherText = "";
    printf("Plaintext: %s, key: %i\n", text, key);

    key = key % 26;

    for (int i = 0; i < strlen(text); i++) {
        if ((text[i] >= 'A' && text[i] <= 'Z') || (text[i] >= 'a' && text[i] <= 'z')) {
            text[i] = (int) text[i] + key;
        }
        cipherText +=  text[i];
    }
    return cipherText;
}

为什么我返回的密文字符串是空的?它不是 for 循环中的同一个变量吗?它是来自 EdX https://ide.cs50.io的云 IDE ,它们在cs50.h中有一个字符串类型

标签: cscopecs50

解决方案


假设这string是 , 的别名char*cipherText += text[i];不是连接字符串而是移动指针。

您应该像这样分配一个缓冲区并将结果存储在那里:

string getCipherText(string text, int key) {
    size_t len = strlen(text):
    string cipherText = malloc(len + 1);
    if (cipherText == NULL) {
        fputs("malloc() failed!\n", stderr);
        return NULL;
    }
    printf("Plaintext: %s, key: %i\n", text, key);

    key = key % 26;

    for (int i = 0; i < len; i++) {
        if ((text[i] >= 'A' && text[i] <= 'Z') || (text[i] >= 'a' && text[i] <= 'z')) {
            text[i] = (int) text[i] + key;
        }
        cipherText[i] =  text[i];
    }
    cipherText[len] = '\0';
    return cipherText;
}

推荐阅读