我的目标是制作一个 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;
}