0

My errors: :( rejects "Hax0r2" as keyword

\ expected output, not a prompt for input

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

int main(int argc, string argv[])
{   
    if(argc != 2) // only 2 arg
    {
        printf("Retry, max 1 key\n");
        return 1;
    }

// variable declerations 
string p = GetString();
string key = argv[1];
int key_lenght = strlen(key);
int p_lenght = strlen(p);
int key_int[key_lenght];
int p_int[p_lenght];


for(int x = 0; x < key_lenght; x++)
{
    // stops you from entering non-alphas as a key
    if(!isalpha(key[x]))
    {
        printf("Keyword must only contain letters A-Z and a-z\n");
        return 1;
    }
    // loops through key & inserts its "ASCII integers" into an array
    if(isupper(key[x]))
    {
        key_int[x] =(int) key[x] - 65; 
    }
    if(islower(key[x]))
    {
        key_int[x] =(int) key[x] - 97;
    }
}

 // loops through inputed p
for(int i = 0, j = 0; i < p_lenght; i++)
{
    // if you write a non alpha as text, it wont encrypt it
    if(!isalpha(p[i]))
    {
        printf("%c", (char) p[i]);
    }
    if(isupper(p[i]))
    {   
        // changes the upperC letters into alphabet-ints
        p_int[i] = (int) p[i] - 65; 

        // formula to encrypt
        int encrypted = (p_int[i] + key_int[(j % key_lenght)]) % 26; 

        // from integer to a letter
        printf("%c", (char) encrypted + 65); 

        j++; // j = order of encryption from 0..3..7...
    }
    if(islower(p[i])) // same as above but for L-case letters
    {
        p_int[i] = (int) p[i] - 97;
        int encrypted = (p_int[i] + key_int[(j % key_lenght)]) % 26;
        printf("%c", (char) encrypted + 97);
        j++;
    }
}
printf("\n");

}

  • Sorry for the bad style and design, I am new to programming – Daniel Jul 7 '16 at 18:27
1

There's a small mistake in the way you have written the code. You are expected to first check whether the keyword is valid or not. If it turns out to be valid, only then you must prompt user for input of message.

However, in your program, you are directly asking the user for input of message (using string p = GetString();), without verifying the keyword. Since, Hax0r2 is not a valid keyword, your program must reject it with an error message, without asking for any input.

(If it helps, do upvote and mark it as correct answer!)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .