首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >CS50凯撒密码虫

CS50凯撒密码虫
EN

Stack Overflow用户
提问于 2022-02-26 02:07:50
回答 1查看 374关注 0票数 1

好吧,所以我完全不知所措了。我不明白为什么这个程序输出每次都像一个随机密钥一样工作。

这个项目:

代码语言:javascript
复制
#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, string argv[])
{
    string sKey = argv[1];
// Make sure program was run with just one command-line argument
    if (argc != 2 || atoi(argv[1]) < 0)
    {
        printf("Usage: ./caesar key\n");
        return 1;
    }

//Counts length of string and checks if all chars are digits
    int counter = 0;
    for (int i = 0; i < strlen(sKey); i++)
    {
        if isdigit(sKey[i])
        {
            counter++;
        }
    }

//Checks if the key is a number
    if (counter != strlen(sKey))
    {
        printf("Usage: ./caesar key\n");
        return 1;
    }

// Convert argv[1] from a `string` to an `int`
    int key = (int)sKey;

// Prompt user for plaintext
    string plaintext = get_string("Plaintext:  ");
    printf("Ciphertext: ");
    for (int i = 0; i < strlen(plaintext); i++)
    {
        if (isalpha(plaintext[i]) && isupper(plaintext[i]))
        {
            printf("%c", (((plaintext[i] - 'A') + key) % 26) + 'A');
        }
        else if (isalpha(plaintext[i]) && islower(plaintext[i]))
        {
            printf("%c", (((plaintext[i] - 'a') + key) % 26) + 'a');
        }
        else
        {
            printf("%c", plaintext[i]);
        }
    }
    printf("\n");
}

将输出以下内容:

代码语言:javascript
复制
caesar/ $ ./caesar 1
Plaintext:  Hello, I'm Justin.
Ciphertext: Fcjjm, G'k Hsqrgl.
caesar/ $ ./caesar 1
Plaintext:  Hello, I'm Justin.
Ciphertext: Pmttw, Q'u Rcabqv.

这似乎是由于模块化操作符,因为当我隔离它时,我可以重新创建这个问题。这是我收藏的图书馆吗?我自己解决了这个问题,最后在youtube上找到了一个解决方案,结果却发现我的解决方案执行了与正确解决方案相同的操作。我一定是漏掉了什么。

谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-02-26 02:26:04

这是因为int key = (int)sKey;没有将字符串转换为整数.至少不像你想的那样。它使用指向整数的字符串指针sKey (内存地址)。因为每次运行progra时,这个地址可能是不同的,这就是为什么它看起来是随机的。将数字字符串转换为值的正确方法是使用atoistrtol。程序的第一部分应该是这样的:

代码语言:javascript
复制
#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, string argv[])
{
    string sKey = argv[1];
    int i;

    // Make sure program was run with just one command-line argument
    if (argc != 2)
    {
        printf("Usage: ./caesar key\n");
        return 1;
    }

    // Checks if all chars are digits
    for (int i = 0; sKey[i]; i++)
        if (!isdigit(sKey[i]) break;

    // If the key contains any non-digits, error
    if (sKey[i])
    {
        printf("Usage: ./caesar key\n");
        return 1;
    }

    // Convert argv[1] from a `string` to an `int`
    int key = atoi(sKey);

// The rest should be fine
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71273545

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档