请看一下下面的代码和屏幕截图。由于某种原因,它打印了 3 个空格,从而将键 2 移动了太多。
代码实际上应该像这样:
Plaintext: M|e|e|t| |m|e| |a|t| |t|h|e| |P|a|r|k
Keyword: a|b|c|d|e|a|b|c|d|e|a|b|c|d|e|a|b|c|d
Move letter by: 0|1|2|3|4|0|1|2|3|4|0|1|2|3|4|0|1|2|3|
但由于某种原因,它不会像“Meet”后面那样在“me”后面加一个空格,而是在“meet”后面加3个空格...
是的,我尝试自己调试它。
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(int argc, string argv[1])
{
bool keySuccesful = false;
string keyword;
do
{
// Check whether argc is 2. If not print the following. Else turn argv[1] into an int and set keySuccesful to true.
if (argc != 2)
{
printf("You didn't submit a valid encryption key.\n");
printf("Please check your input and re-run the programm.\n");
printf("We require an integer as encryption key.\n");
return 1;
}
else
{
// Key needs to be converted from string to int
keyword = argv[1];
keySuccesful = true;
}
} while (!keySuccesful); // repeat while keySuccessful is false.
string plain = get_string("plaintext: "); // Get plaintext/
printf("ciphertext: "); // Print "ciphertext: "
for (int k = 0; k < strlen(plain); k++) // loop through each character of the plaintext, start at index 0, until the length of the string.
{
for (int u = 0; u <strlen(keyword); u++)
{
int g = keyword[u] - 97;
if(isalpha(plain[k])) // check that chacater is a letter
{
if (isupper(plain[k])) // if letter is uppercase
{
printf("%c", ((((plain[k] - 65)+g)%26)+65));
}
if (islower(plain[k])) // if letter is lowercase
{
printf("%c", ((((plain[k] - 97)+g)%26)+97));
}
k++;
}
else
{
printf("%c", plain[k]);
}
}
}
}
最佳答案
我认为问题在于您仅增加 k
里面isalpha
堵塞。因此,一个空间将/可能被处理多次,即直到 for (int u = 0; u <strlen(keyword); u++)
结束。
尝试:
// k++; Remove this line
}
else
{
printf("%c", plain[k]);
}
k++; // Insert this line
此外,您的嵌套循环是错误的,因为您可能会增加 k
内循环太多,因此读取越界。
考虑改变
for (int u = 0; u <strlen(keyword); u++)
至
for (int u = 0; u <strlen(keyword) && k < strlen(plain); u++)
注意:您的代码似乎适用于第一个空格的原因是“Meet”恰好与您的关键字具有相同的长度。因此,内部循环在处理一次空格后恰好停止。但对于“me”来说,情况并非如此,因此将打印额外的空格
关于c - 为什么我的代码在加密第二个单词后插入了 3 个空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48238654/