0

I know a similar question has been asked about this, but I don't know how to apply the answer to my code! I've been stuck for so long so I thought I'd request some help!

My problem is that, my code continues to rotate over non-alphas in the key. I KNOW it's to do with my for loop, and the fact that the functions at the bottom are related to i. However I can't for the life of me figure out how to start a new function to avoid this.

Any guidance is super super appreciated! :) :)

    #include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h> // for atoi(), string to int
#include <ctype.h>

// declarations of functions
int upperConv(int input, int key);
int lowerConv(int input, int key);

// accepts command line argument
int main(int argc, string argv[])
{   
if(argc != 2)
{
    printf("Error. Please enter one additional arugment after ./caeser\n");
    return 1;
}

// retrieve key from second argument (ie argv[1])
string key = argv[1]; 

for(int j = 0, m = strlen(key); j < m; j++)
{  
    if (!isalpha(key[j]))
    {
        printf("Non alpha-neumeric character in key. Please enter only letters. \n");
        return 1; 
    }
}

string input = GetString();

for(int i = 0, n = strlen(input); i < n; i++)
{        

        if (isupper(input[i]))
        {            
            printf("%c", upperConv(input[i], key[i%3])); 
        }
        else if (islower(input[i]))
        {            
            printf("%c", lowerConv(input[i], key[i%3]));
        } 
        else if (!isalpha(input[i]))
        {
           printf("%c", input[i]);              
        }      

}    

printf("\n");

return 0;
}

int upperConv(int input, int key)
{
int offset = key - 65;
int x = input - 65 + offset;
int upper = x % 26;
upper = upper + 65;
return upper;
}

int lowerConv(int input, int key)
{
int offset = key - 97;
int x = input - 97 + offset;
int lower = x % 26;
lower = lower + 97;
return lower;
}
1

This is a very common error. You are rotating through both the key and the plain text with the same index, so no matter what, key is going to index with EVERY character processed in the plain text, even if it isn't encoded.

You need to use a separate index to track through the key, and only increment it when something is actually encoded from the plain text. When something is only copied, like a number, space or punctuation, then you don't change the key index.

You have a second problem waiting. This code would only work for a key of 3 elements because you hardcoded a length of 3, i.e., key[i%3]. You need to code it for any key length.

If this answers your question, please click the check mark to accept this and remove the question from the unanswered pool. Let's keep up on forum maintenance. ;-)

1
  • Thanks man, didn't even notice the second error waiting! Sep 6 '15 at 21:00

You must log in to answer this question.

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