#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
int main(int argc, string argv[])
{
if(argc != 2) // RETURNS TO 1 if not 2 strings
{
printf("Usage: ./caesar k\n");
return 1;
}
// calculate length of string and make sure it is alpha
string keyphrase = argv[1];
// k is the keyword wraparound integer get before loop so you can use k
int k;
// Get string length and calculate characters and loop string first for loop here
for (int j = 0, l = strlen(keyphrase); j < l; j++)
{
if(!isalpha(keyphrase[j]))
{
printf("Please ensure all characters are alphabetical.\n");
return 1;
}
else
{
k = j % l;
}
}
// after string of key is validated get the printtext
printf("plaintext: ");
string s = get_string();
printf("ciphertext: ");
// CUT OFF HERE JUST IN CASE and also cipher plain text from here on out also second for loop starts here plain text is also variable s
for(int i = 0, n = strlen(s); i < n; i++)
{
// NOT SURE WHAT TO DO TO MAKE KEYWORD WORK AND LOOP over each plaintext letter
if(isupper(s[i]) && isupper(k))
{
// convert asci to alphbetical for upper case
int cipher = s[i]-'A';
int c = (cipher + k) % 26;
printf("%c", c +'A');
}
//convert for lower case
else if(islower (s[i]) && islower (k))
{
int cipher2 = s[i]-'a';
int d = (cipher2 + k) % 26;
printf("%c", d+'a');
}
//PRint characters
else
{
printf("%c", s[i]);
}
// PASTED CODE ENDS HERE JUST IN CASE
}
//print space after i for loop
printf("\n");
return 0;
}
I feel like I am really close but I am stuck on this last part I am putting in the formula for k but it's not outputting the correct cipher. Anyone have any ideas I would really appreciate it.
k
seems to be some kind of index, why do you treat it like a character then? You need to have an index in the plaintext (youri
), and an index in the cipher (initially 0, incremented whenever you encrypt a letter, wrapping around on reaching cipher length). The letter in the cipher is used Caesar-style in encryption, not its position.k
, orp
, or anything else, just make sure it wraps around and is incremented on encryption only, and you applyislower
ortolower
or something like that only to characters.