C 中的本地范围

Hrv*_*e T 0 c scope cs50

我在 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;
}
Run Code Online (Sandbox Code Playgroud)

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

Mik*_*CAT 5

假设它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;
}
Run Code Online (Sandbox Code Playgroud)