【发布时间】:2012-11-30 07:13:55
【问题描述】:
我的目标是制作一个 Vigenere 密码。我试图通过从 argv 获取密钥,从用户获取字符串,然后通过我创建的一个函数传递消息和密钥,该函数将它们组合并在打印之前返回新值。出于某种原因,它只是在打印密钥。我认为这与新函数以及我如何尝试使用返回值有关。代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <cs50.h>
#include <string.h>
#include <stdbool.h>
#include <ctype.h>
int new_crypt;
int encrypt(string , int );
int main(int argc, string argv[])
{
if( argc != 2)
{
printf("Plese enter only one key");
return 1;
}
string message = GetString();
for(int i=0; i < strlen(message); i++)
{
int klen = strlen(argv[1]);
//repeats the key until the message is over
int key= argv[1][i%klen];
bool kupper = isupper(key);
bool klower = islower(key);
bool kalpha = isalpha(key);
if(kupper == true){
//ASCII value of A is 65. 'A' = 0 shifts
int k = key-65;
int new_crypt = encrypt(message, k);
printf("%c", new_crypt);
}
if(klower == true){
//ASCII value of 'a' is 97. 'a' = 0 shifts
int k = key- 97;
int new_crypt = encrypt(message, k);
printf("%c", new_crypt);
}
if(kalpha == false){
int k = 0;
int i = i-1;
int new_crypt = encrypt(message, k);
printf("%c", new_crypt);
}
}
printf("\n");
return 0;
}
int encrypt(string message, int k)
{
for(int i=0; i < strlen(message); i++)
{
bool upper = isupper(message[i]);
if(upper == true)
{ //Makes sure the message doesnt go past 'Z'.. If it does it mod 90 it / // and adds 65 ('A')
int crypt = (message[i]+ k) % 90;
if(crypt < 65)
{
int new_crypt = (crypt + 65);
return new_crypt;
}
else{
int new_crypt = crypt;
return new_crypt;
}
}
bool lower = islower(message[i]);
if(lower == true)
{
int crypt = (message[i]+ k) % 123;
if(crypt < 97)
{
int new_crypt = crypt + 97;
return new_crypt;
}
else{
int new_crypt = crypt;
return new_crypt;
}
}
bool alpha = isalpha(message[i]);
if(alpha == false)
{
int new_crypt = message[i];
return new_crypt;
}
}
return 0;
}
【问题讨论】:
-
string到底是什么? -
我还在消化
encrypt()的 for 循环中的两个 if-else 块的合理性。稍后我会到达string... -
贴出真实代码,包含标头。
-
我正在使用我正在学习的课程提供的一些预制标头...我的问题纯粹是关于在
main函数中使用encrypt()的返回值。两个 if-else 语句检查消息字符是大写、小写还是非字符。如果是,那么它通过添加带有密钥的消息 char i 来生成crypt。如果字符过去了,例如 90(Z 的 ascii)+ 1,那么它会修改数字并给出 1。由于 1 不等于 A,我必须检查它是否 -
另外,当心
int new_crypt和"%c"。
标签: c encryption return-value cs50 vigenere