好吧,所以我完全不知所措了。我不明白为什么这个程序输出每次都像一个随机密钥一样工作。
这个项目:
#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");
}将输出以下内容:
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上找到了一个解决方案,结果却发现我的解决方案执行了与正确解决方案相同的操作。我一定是漏掉了什么。
谢谢
发布于 2022-02-26 02:26:04
这是因为int key = (int)sKey;没有将字符串转换为整数.至少不像你想的那样。它使用指向整数的字符串指针sKey (内存地址)。因为每次运行progra时,这个地址可能是不同的,这就是为什么它看起来是随机的。将数字字符串转换为值的正确方法是使用atoi或strtol。程序的第一部分应该是这样的:
#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 finehttps://stackoverflow.com/questions/71273545
复制相似问题