Vigenere cypher finished:
I am pretty happy with my development so far, and happy to see I can code basic things in C. It really is interesting to see how basic thigns do become hard, in terms of for example making a tring all to lower case, and having to constantly keep track of each variable and its type.
Now, I feel I am starting to be able to do stuff… but it is true that I don’t feel fully under control. I mean that, I am not 100% sure that I am using everythign in the most efficient way, and that every variable is named in the right way etc.
Will def. take me more time to get used to all of that.
In the meantime… enjoy my code :D!
#include stdio.h #include cs50.h #include string.h #include stdlib.h #include ctype.h bool Check_If_Alpha (); string All_Tolower (); int main (int argc, string argv[]) { // Below I check if input is only alphabetical characters if (argc != 2 || Check_If_Alpha(argv[1]) == 0) { printf("Baad!! I expect only a string of alphab characters\n"); return 1; } string plaintext = GetString(); //Here I make key string all lower case just to simplify later string kstring = All_Tolower(argv[1]); for (int i = 0, n = strlen(plaintext), j = 0; i < n; i++) { int length_key = strlen(kstring); // c is current character int c = plaintext[i]; // As k is only lower, its easy to convert to 0-25 index by doing -97 // This means that "a" won't be 97, it will be 0 etc. int k = kstring[j] - 97; if (isalpha(c)) { // if current char is alphab, then it proceeds to the conversion if (isupper(c)) { int dec_upper = ((c - 65) + k) % 26; int ascii_upper = dec_upper + 65; printf("%c", ascii_upper); j = ((j + 1) % length_key); } else { int dec_lower = ((c - 97) + k) % 26; int ascii_lower = dec_lower + 97; printf("%c", ascii_lower); j = ((j + 1) % length_key); } } else { printf("%c", c); } } printf("\n"); return 0; } // This function checks if the input is a positive integer bool Check_If_Alpha (string a) { for (int i = 0, n = strlen(a); i < n; i++ ) { // if the character is not an alphabetical one if (isalpha(a[i]) == 0) { return 0; } } return 1; } // This function turns a string all to lower case string All_Tolower (string a) { for(int i = 0; a[i]; i++) { a[i] = tolower(a[i]); } return a; }