I have included the part of my cypher responsilble for converting a command line keyword into an array of integers that will indicate by how much each character in a phrase should be shifted in encryption. Ideally, if I enter 'a' as the keyword and 'a' as the phrase to be encrypted, the resulting encryption should be 'b'. As of now though, I get 'K'.

I have included a printf check to see how much the keyword is shifting the phrase, which for the above circumstances is a shift of -48. It should be a shift of 1.

Can anyone tell me how I messed up? I've been trying to figure this out for quite a while.

//prompt the user for a non-neg integer 'k' which is to be used as
//an arg

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

int main (int argc, char *argv[])
    if (argc!=2)                //fail if 0 or more than one key
        return 1;

    int keylength=strlen(argv[1]);   // get length of keyword

    int newkey[keylength];
    //deal with upper and lower case chars in keyword first
    for (int j=0; j<keylength; j++) //iterate through each char in key
        if (islower(argv[1][j]))   //if key char is lower case...
            int x = (argv[1][j])-'0';
            int y = x-97;
            newkey[j]= y;  
        if (isupper(argv[1][j]))   //if key char is upper case...
            int x = (argv[1][j])-'0';
            int y = x-65;
    printf ("%i\n", newkey[0]);

1 Answer 1


int x = (argv[1][j])-'0'; looks like your problem. You are subtracting the ascii value of the 0 symbol from the character in argv[1][j]. In effect, you have done int x = (argv[1][j])-48; I don't understand why you are subtracting either 0 or the ascii value of 0 here.

Instead of those 3 lines of code, you could consolidate them into one line and eliminate the intermediate variables.

    newkey[j] = (argv[1][j])-'a';

Why not keep it simple?

If this answers your question, please click on the check to accept. Let's keep up on forum housekeeping. ;-)

  • I see, I was trying to convert argv[1][j] to an integer but I guess this was an incorrect way to do so. I thought that the ascii value of '0' is zero, so the only thing that happens is it converts the char to an int. So this assumption is wrong? As for your solution to subtract 'a', is that the same as subtracting 97? Could i replace "-'a'" with "-97"?
    – noggy
    Oct 6, 2015 at 0:24
  • a char actually behaves like a 1 byte signed integer, so you can do math operations on a char without any explicit conversions. You could do an explicit cast, if you really feel the need. (Can't remember if casting has been taught by this lesson.) Yes, you could replace 'a' with 97, either will work.
    – Cliff B
    Oct 6, 2015 at 0:31

You must log in to answer this question.

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