0

I am very new to coding and cant tell where the problem with this is. It does compile however when run it returns the string exactly as it was input, including non alphabetic characters. I'm unsure of what the problem with this part of the code is. (Apologies for having no comments and rather messy code).

 for (int b = 0, k = strlen(key); b < k; b++)
 {
    if(!isalpha(key[b]))
    {
        printf("Keyword contains non aplphabetic characters. Termitating program.");
        return 1;
    }
}

the for loop works as intended however the if loop gets skipped over.

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

string t;

int main(int argc, string argv[])
{


if (argc != 2)
{
    printf("missing command-line argument: single keyword\n");
    return 1;
}

string key = argv[1];




for (int b = 0, k = strlen(key); b < k; b++)
{
    if(!isalpha(key[b]))
    {
        printf("Keyword contains non aplphabetic characters. Termitating program.");
        return 1;
    }
}


int d = 0;





    printf("Enter a string:\n");
    t = get_string();



        for (int j = 0; j < strlen(t); j++)
        {
            if (isalpha(t[j]))
            {

               if (isupper(t[j]))
               {
                  d = ((int)t[j] - 65);
                  d += ((key[k] - 65)%1);
                  d %= 26;
                  d += 65;
                  printf("%c", d);

               }

               if (islower(t[j]))
               {
                   d = ((int)t[j] - 97) + ((key[k] - 97)%1);
                   d %= 26;
                   d += 97;
                   printf("%c", d);
               }
            }
            else
            {
                printf("%c", t[j]);
            }



        }

    printf("\n");

}
0

You assign

k = strlen(key)

which means

key[k] == '\0'

(the null terminator), but you ignore the result of key[k] anyway, as

((key[k] - 65)%1)

evaluates to 0 for any integer. There's no need for a modulo operation at that point, but you could use something like toupper(key[k]) - 65 to ignore case in the key.

You'll need some index variable, initially 0, which is incrementing on encrypting a character, and wraps around at strlen(key). That might be k, but not with that static value.

You must log in to answer this question.

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