簡體   English   中英

C - 更改字符串似乎以相同的方式更改不相關的字符串 (CS50)

[英]C - Changing a string seems to change unrelated strings in the same way (CS50)

這是代碼:

#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>


int main(int argc, string argv[])
{
    string key = argv[1];
    string keyupper = argv[1];
    string keylower = argv[1];


    if (argc != 2) //makes sure there is exactly 2 arguments (the program executable and the key)
    {
        printf("Please input a key.\n");
        return 1;
    }

    else if (strlen(key) != 26) //makes sure the key is exactly 26 letters
    {
        printf("Please make sure the key is 26 unique letters.\n");
        return 1;
    }



    for (int i = 0; i < 26; i++) //the loop to make the uppercase key
    {
        keyupper[i] = toupper(keyupper[i]);
    }



    for (int i = 0; i < 26; i++) //the loop to make the lowercase key
    {
        keylower[i] = tolower(keylower[i]);
    }

本質上,我想使用執行程序時輸入的密鑰進行非常基本的加密,它需要包含 26 個唯一字母。 我想創建兩個 arrays,一個大寫和一個小寫,以使其他一切對我來說更容易,但是在運行此代碼時,所有鍵都變為大寫或小寫,具體取決於最后創建的循環(在這種情況下,它們都變成小寫)。 即使key僅用作聲明一次,它也會更改為小寫。 除了這個,其他一切都有效。

這是針對 CS50 課程的,因此庫中包含諸如toupper()之類的函數。

這是我的第一個問題,如果措辭不好,非常抱歉。 謝謝!

代碼復制字符串內容失敗

[這里說的是字符串,不是string類型]

在 C 中,字符串是“......是一個連續的字符序列,以第一個 null 字符結尾並包括該字符。”

代碼只復制了指針而不是字符串內容。

string key = argv[1];
string keyupper = argv[1];
string keylower = argv[1];

評論討論表明 OP 現在知道代碼錯誤的原因。

修復代碼

//#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>

// Avoid naked magic numbers, instead define them
#define KEY_N 26

int main(int argc, string argv[]) {
    // Do not code argv[1] until after argc check
    // string key = argv[1];
    // string keyupper = argv[1];
    // string keylower = argv[1];

    if (argc != 2) {
        printf("Please input a key.\n");
        return 1;
    }

    char *key = argv[1];
    // else if (strlen(key) != 26)letters
    if (strlen(key) != KEY_N) {
        printf("Please make sure the key is 26 unique letters.\n");
        return 1;
    }

    char keyupper[KEY_N + 1];
    char keylower[KEY_N + 1];

    // for (int i = 0; i < 26; i++)
    for (size_t i = 0; i < KEY_N; i++) {
        keyupper[i] = toupper(keyupper[i]);
    }
    keyupper[KEY_N] = '\0';
    ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM