0

I am trying to write some code for the Substitution question in Problem Set 2, but I cannot figure out how to reject the case where a user gives a key with repeated letters. My code thus far is as follows:

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

int main(int argc, string argv[])
{
    int n = strlen(argv[1]);
    if (argc == 2 && n == 26)
    {
        for (int i = 0; i < n; i++)
        {
            if (!(isalpha(argv[1][i])))
            {
                printf("Please enter a valid substitution key in the command-line. Your key must only contain 26 letters of the alphabet and they have to be unique.\n");
                return 1;
            }
        }
    }
    else
    {
        printf("Please enter a valid substitution key in the command-line. Your key must only contain 26 letters of the alphabet and they have to be unique.\n");
        return 1;
    }
}

I know that if I were to enter a key with 26 characters, but some repeated, my code would accept it when it should not. I have tried to Google an answer for this, but the solutions I have found are beyond my current comprehension of C. Any ideas on how my code can be tweaked to consider this case will be greatly appreciated!

1

simple. two nested for loops to compare each letter to every letter that follows.

| improve this answer | |
  • Thank you for your suggestion! I think this helped me greatly! – Ethan Mark Jun 3 at 8:57
1

Put a nested loop to compare each letter to all the others. An example would be

for (int i = 0; i < 26; i++)
{
for (int j = 0; j < 26; j++)
{
if(i == j)
{

}
else
{
if(argv[1][i] == argv[1][j])
{

}
else
{
printf("Please enter a valid substitution key in the command-line. Your key must only contain 26 letters of the alphabet and they have to be unique.\n");
return 1;
}
}
}
}

If this was helpful, click the check mark.

| improve this answer | |
  • Thank you for your input :) I was already on to nesting two for loops, but I did not realise that I had some minor logical flaws in my code. Your input definitely helped me to refine it, but as Cliff B had given me the idea first, I accepted his as the answer. Apologies for that, although I did upvote yours as well! – Ethan Mark Jun 3 at 8:59

You must log in to answer this question.

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