Ad

Cs50 - Pset 2 - Substitution Program

- 1 answer

I was doing the cs50 pset 2 - substitution, where we have to encrypt the plaintext using the key given by the user in the command line, but the following code isn't prompting for an input. What am I doing wrong? Any help would be greatly appreciated!

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

int check(int c, string key);

int main(int argc, string argv[])
{
    int checkR = check(argc, argv[1]);
    if(checkR == 1)
    {
        return 1;
    }
    else
    {
        string key = argv[1];
        string ptext = get_string("plaintext: ");
        int len = strlen(ptext);
        char ctext[len];
        for (int i = 0; i < len; i++)
        {
            if(isupper(ptext[i]))
                ctext[i] = toupper(key[(int)ptext[i] - 65]);
            else if(islower(ptext[i]))
                ctext[i] = tolower(key[(int)ptext[i] - 97]);
            else
                ctext[i] = ptext[i];
        }
        printf("ciphertext: %s\n", ctext);
        return 0;
    }
}

int check(int c, string key)
{
    int keyL = strlen(key);
    
    if(c != 2)
        return 1;
        
    else if(keyL != 26)
        return 1;
    
    for(int i = 0; i < keyL - 1; i++)
    {
        for(int j = i; j < keyL; j++)
        {
            if(key[i] == key[j])
                return 1;
        }
    }
    
    return 0;
}
Ad

Answer

Answer for the question

In the check function, you initialized the inner loop as int j = i.
Therefore, in the first iteration, key[i] == key[j] will be always true.
Then, 1 is returned from check and it prevents main function from printing the prompt.
The initialization should be int j = i + 1.

Other mistakes

Firstly, it is bad to do int keyL = strlen(key); before checking c because key (argv[1]) may be NULL when c (argc) is less than 2.

Secondly, printf("ciphertext: %s\n", ctext); in this code will invoke undefined behavior because what is stored in ctext is not NUL-terminated.
char ctext[len]; should be char ctext[len+1]; and ctext[len]='\0'; should be added before printf("ciphertext: %s\n", ctext);.

Ad
source: stackoverflow.com
Ad