1

The program is working but in the wrong digits. It suppose to print out "e" when the key=1 and string=a. But i don't know how come the result is "h"? Are there any problem in my constant?

really thank you for the answer!!

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

int main (int argc, string argv[ ]) 
{
    if (argc !=2)
    {
       printf("Usage: ./asciimath key"); 
       return 1;
    }

    int k = atoi(argv[1]);
    string s = GetString();

    for(int i=0, n=strlen(s); i<n; i++)
    {
        if (isalpha(s[i]))
        {
            char a = s[i] - 65;
            char b = (a + k) % 26;
            char c = (b +65);

        printf("%c", c);
        }

        else
        {
            printf("%c", s[i]);
        }
    }
    printf("\n");

    return 0;

}
1

Two related problems. First, 'a' = 97, 'A' = 65, so you're subtracting the wrong value for lower case letters. Since the ASCII numbers of upper case and lower case letters differ by 32, and 32 - 26 = 6, guess what happens.

Second, the code doesn't check whether the letter being encoded is upper or lower case at all. As written, this code will only encode upper case letters correctly.

You have some code to add and change in your program.

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

3
  • Really thanks a lot!! I figured out this morning too!!
    – Beta Lee
    Sep 6 '16 at 0:22
  • so I divide the chars into 3 type: for(int i=0, n=strlen(s); i<n; i++) { if (('A'<= s[i]) && (s[i]<='Z')) { char a = s[i] - 65; char b = (a + k) % 26; char c = (b +65); printf("%c", c); } else if (('a'<=s[i]) && (s[i]<='z')) { char d = s[i] - 97; char e = (d + k) % 26; char f = (e +97); printf("%c", f); } else { printf("%c", s[i]); } return 0; }
    – Beta Lee
    Sep 6 '16 at 0:24
  • That looks like you're on the right track. You might also find isupper(), islower() isalpha() useful. There are also tolower() and toupper() but those might not be useful yet. ;-)
    – Cliff B
    Sep 6 '16 at 0:27

You must log in to answer this question.

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