c - Vigenere cs50 Pset2 末尾的额外字符
问题描述
我是编码新手,已经做了几个星期了。我现在正在学习 cs50 课程,并且我已经为 pset2 vigenere 编写了代码。当我使用 check50 时,我意识到它希望我在不跳过键的情况下考虑空格和非字母。
我添加了“j--;” 而且,虽然代码是正确的,但它现在在密文末尾创建了额外的随机字符。
此外,在我的代码中仅检查 argv[1] 时,我有一个 if 语句,其中包含“int key = argv[1][i];” 在身体里。它什么也没做,但我不知道如何让它继续检查下一个字符而没有空的正文,这是不允许的。
任何帮助,将不胜感激!非常感谢!
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(int argc, string argv[0])
{
//making sure it is not more than one command line
if (argc != 2)
{
printf("Usage: ./vigenere key \n");
return 1;
}
//if it is one command line, making sure the input is just letters
if (argc == 2)
{
for (int i = 0, n = strlen(argv[1]); i < n; i++)
{
if (isalpha(argv[1][i]))
{
int key = argv[1][i];
}
else
{
printf("Usage: ./vigenere key \n");
return 1;
}
}
}
//asking user for input text
string plaintext = get_string("plaintext: ");
printf("ciphertext:");
//going through a loop to turn plain text into ciphertext
int i = 0;
int n = strlen(plaintext);
string key = argv[1];
//looping through the key
while (i < n)
{
for (int j = 0, m= strlen(key); j < m; j++, i++)
{
//using the asci of each char as an int
int asc = (plaintext[i]);
int k = key[j];
//if lowercase
if (k >= 97 && k <= 122)
{
k -= 97;
}
else
{
k -= 65;
}
//if lowercase
if (asc >= 97 && asc <= 122)
{
printf("%c", ((((asc - 97) + k) % 26) + 97));
}
//if uppercase
else
{
if (asc >= 65 && asc <= 90)
{
printf("%c", ((((asc - 65) + k) % 26) + 65));
}
//if non-letter
else
{
printf("%c", asc);
j--;
}
}
}
}
printf("\n");
}
这些是预期结果与实际结果:
key: baz
plaintext: hello, world!
expected ciphertext: iekmo, vprke!
actual ciphertext: iekmo, vprke!!pu
解决方案
i
因为程序在此处递增for (int j = 0, m= strlen(key); j < m; j++, i++)
,所以它允许读取明文末尾。i
在 for 循环完成之前,while 循环不会计算。这有可能无限循环,具体取决于明文结束后内存的内容。如果它永远不会遇到 az 或 AZ 范围内的东西,它将j--
永远。
你需要在 if 和 when 中跳出 for 循环i == strlen(plaintext)
。
推荐阅读
- tornadofx - replaceWith() 方法的 sizeToScene 属性切割顶部并增加窗口的底部
- javascript - Wordpress - JS 仅选择我点击关注的当前用户
- react-native - 如何使不规则设计响应原生反应?
- python - 如何通过 Python 脚本运行 sikuli 脚本
- python-3.x - 是否可以选择在数组中查找数组?
- vue.js - 在本地 https 上运行 nuxt – nuxt.config.js 的问题
- azerothcore - 未找到艾泽拉斯核心模块配置
- python - Context_processor 未定义“”类/属性(错误)
- sql - 在postgres中如何找到最短的字符串数组
- c - 在包含字符串的 typedef 结构中使用指针