繁体   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