I have been struggling a lot with vigenere and I am seeing the light. The only thing I have left to do is understanding how to take into account the z character when doing modulo 97. my code work with a z key until the letter e and then stops working. I am not sure why. I have already seen this topic and this one but I am not sure how to integrate them in my code.
Code Update#1:
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
string k;
int p;
int j;
int main(int argc, string argv[])
{
if (argc > 2 || argc < 2)
/*make sure there are two argument */
{
printf("error 1 \n");
return 1;
}
else
{
k = argv[1];
p = strlen(k);
for (int f = 0; f < p; f++)
{
/*loop */
if (!isalpha(k[f]))
{
printf("error 1 \n");
/*take every character of argv[1] and make sure alphabetical */
return 1;
}
/* make every letter in k a lowercase*/
if (isupper(k[f]))
{
k[f] = tolower(k[f]);
}
}
printf("plaintext:");
/*prompt get_string */
string s = get_string();
printf("ciphertext:");
/* loop for every letter in s*/
for (int i = 0, n = strlen(s); i < n ; i++)
{
/*make sure si is alphabetical*/
if (isalpha(s[i]))
{
// if (s[i] < 0)
// {
// s[i] = s[i] * (-1);
// }
/*loop k if i is greater than p*/
if ((i > p))
{
k[i] = k[i % p];
}
/*for i capital*/
if (isupper(s[i]))
{
/*getting order in the alphabet and adding them*/
s[i] = ((((s[i]) - 65) + ((k[i]) - 97)) + 65);
/*looping to stay in the 65-90 interval*/
while ((s[i]) > 90)
{
s[i] = s[i] - 26;
}
}
if ( islower(s[i]))
{
s[i] = ((((s[i]) - 97) + ((k[i]) - 97)) + 97);
/*looping to stay in the 97-122 interval*/
while ((s[i]) > 122)
{
s[i] = s[i] - 26;
}
}
}
else
{
s[i] = s[i];
}
printf("%c", s[i]);
}
}
/*gives answer*/
printf("\n" );
return 0;
}
Old code:
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
string k;
int p;
int j;
int main(int argc, string argv[]){
k=argv[1];
p=strlen(k);
if (argc>2||argc<2){ /*make sure there are two argument */
printf("error 1 \n");
return 1;
}
else{
for (int f=0; f<p; f++){ /*loop */
if (!isalpha(k[f])){ /*take every character of argv[1] and make sure it is alphabetical */
printf("error 1 \n");
return 1;
}
if (isupper(k[f])){
k[f]=tolower(k[f]);
}
}
printf("plaintext:"); /*prompt get_string */
string s= get_string();
printf("ciphertext:");
for (int i=0, n = strlen(s); i<n ; i++){ /*loop for i */
if (isalpha(s[i])){
if(s[i]<0){
s[i]= s[i]*-1;
}
if((i>=p)){
k[i]=k[i%p];
}
if(isupper(s[i])){
s[i]=(s[i]+((k[i])%97));
while (s[i]>90){
s[i]=((s[i])-26);
}
}
if(islower(s[i])){
s[i]=(((s[i]))+((k[i])%97));
while (s[i]>122){
s[i]=((s[i])-26);
}
}
}
else{
s[i]=s[i];
}
printf("%c", s[i]);
}
}
/*gives answer*/
printf("\n" );
return 0;
}