I have been stuck on vigenere for two weeks now, and I think that I am almost there. My code prints out some correct characters, but also some incorrect ones. I think that it has something to do with my wraparound, but before I added one piece of code my wraparound worked fine.
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
int letter;
int counter = 0;
char kk;
char cc;
int main(int argc, char* argv[]) {
// Returns error if the command line arguments are not up to specifications
if (argc < 2 || argc > 2) {
// Returns value of error code
return 1;
// Else runs the cypher as usual
} else {
// Defines codeword and text to be coded
char* code = argv[1];
char* text = GetString();
// Defines length variables
int clength = strlen(code);
int tlength = strlen(text);
// Encrypts text
for (int i = 0; i < tlength; i++) {
// If the character is a space, ignores it
if (text[i] == ' ') {
printf(" ");
// Else continues encrypting
} else {
// Checks to see if the letter is alphabetical
if (isalpha(text[i])) {
// If the letter is capital
if (isupper(text[i])) {
// Determines what to add to the text
if (isupper(code[(counter % clength)])) {
kk = code[(counter % clength)] - 'A';
} else if(islower(code[(counter % clength)])) {
kk = code[(counter % clength)] - 'a';
}
// Writes out the letter
letter = (char)((text[i] + (char)kk) % 26);
// If the letter is lowercase
} else if(islower(text[i])) {
// Determines what to add to the text
if (isupper(code[(counter % clength)])) {
cc = code[(counter % clength)] - 'A';
} else if(islower(code[(counter % clength)])) {
cc = code[(counter % clength)] - 'a';
}
// Writes out the letter
letter = (char)((text[i] + (char)cc) % 26);
// Else if the letter is not either (a character)
} else {
// Letter is the same
letter = (text[i]);
}
// Increments counter
counter++;
// Else if the letter is not either (a character)
} else {
// Letter is the same
letter = text[i];
}
// Prints out coded text
printf("%c", (int)letter);
}
}
// Prints new line
printf("\n");
// Returns no errors
return 0;
}
}