Faiz Momin Faiz Momin - 3 months ago 7
C Question

Program works but has 1 bug

My program works fine except when I enter a command line input of BaZ and an input of BaRFoo. The program should encrypt it as CaQGon, however it outputs CaQGoh instead. I am really confused as to why this happens because the program works fine for any other key and input. It is just this specific combination that doesn't work. BTW, my program is supposed to encrypt using the vigenere cipher.

#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

string input;
int digitnum = 0;
string keyInput;

int main(int argc, string argv[])
{
keyInput = argv[1];

if (argc>2 || argc<2)
{
printf("Please enter a valid argument.n");
return 1;
}

for (int n = 0, keylength = strlen(argv[1]); n < keylength; n++)
{
if ((keyInput[n] >= '0') && (keyInput[n] <= '9'))
{
printf("Please enter an alphabetical keyword.");
return 1;
}
}

input = GetString();

for (int i = 0; i < strlen(input); i++)
{
char c = input[i];

if (isalpha(input[i]))
{
char currentletter = input[i];
int letternum = currentletter;
char currentkey = keyInput[digitnum];
int currentkeynum = currentkey;

if(isupper(c))
{
int upper = 'A';
int alphanum = letternum - upper;
int key = currentkeynum - upper;
int newint = (alphanum + key) % 26;
newint = newint + upper;
char newchar = newint;
printf("%c", newchar);
}
if(islower(c))
{
int lower = 'a';
int alphanum = letternum - lower;
int key = currentkeynum - lower;
int newint = (alphanum + key) % 26;
newint = newint + lower;
char newchar = newint;
printf("%c", newchar);
}

digitnum = digitnum + 1;

if (digitnum >= strlen(keyInput))
{
digitnum = 0;
}
}
else
{
printf("%c", input[i]);
}
}
printf("\n");
}

Answer

This line

int key = currentkeynum - lower;

will fail when currentkeynum is uppercase, something you do not check for. Your code only works when the key and the message letters both have the same case.

Input: BaRFoo
Key:   BaZBaZ

You can see they match case until you reach the last letter.