0

I have almost finished substitution. Just that I have not yet been able to come up with a elegant way to check if all the characters in the key are distinct hence I used the following way to check if each one is no equal to to the other. I think this should work but the code fails the check 50 test.

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

bool check_char(string s);
int main(int argc, string argv[])

{
    if (argc == 2 && argv[1][1] != argv[1][2] != argv[1][3] != argv[1][4]!= argv[1][5]!= argv[1][6]!= argv[1][7]!= argv[1][8]!= argv[1][9]!= argv[1][10]!= argv[1][11]!= argv[1][12]!= argv[1][13]!= argv[1][14]!= argv[1][15]!= argv[1][16]!= argv[1][17]!= argv[1][18]!= argv[1][19]!= argv[1][20]!= argv[1][21]!= argv[1][22]!= argv[1][23]!= argv[1][24]!= argv[1][25]!= argv[1][26])
    {
    int n = strlen(argv[1]);
    if (n == 26 && !check_char(argv[1]))
    {
        string plain = get_string("plaintext: ");
        printf("ciphertext: ");
        for (int j = 0, len = strlen(plain); j < len; j++)
        {
            if (isupper(plain[j]))
            {
            printf("%c", toupper(argv[1][((int)plain[j] - 65) % 26]));
            }
            else if (islower(plain[j]))
            {
            printf("%c", tolower(argv[1][((int)plain[j] - 97) % 26]));
            }
            else
            {
            printf("%c", plain[j]);
            }

         }
         printf("\n");
         return 0;
    }
    else
    {
        printf("Key must contain 26 characters.");
        return 1;
    }
    
    }
    else
    {
        printf("Usage: ./substitution key");
        return 1;
    }
}
bool check_char(string s)
{
    for (int i = 0, len = strlen(s); i < len ; i++)
    if (isdigit(s[i]))
    {
        return 1;
    }
    return 0;
}

What is wrong with this approach aside from the fact that it is not the best way?

I also don't know why some portion of code is in italics. Please comment if you know how to correct it.

2 Answers 2

2

For starters, you can't chain an entire series of comparisons together like that. It just doesn't work. C has no ability to stack all those comparisons together and figure out that you want to compare the first item to the 4th or last items.

This calls for two nested for loops to walk through the list of items and to compare each item to all the other items in the list.

1
  • that's what i was guessing as well thanks will try to create a function to do the job Commented Oct 9, 2020 at 19:41
0

I agree that two nested loops are necessary.

My question has to do with how to organize those nested loops. Is this like the Mario problem and the pyramids?

You must log in to answer this question.

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