0

I am getting the correct result from the CS50 Vigenere as long as argc does not equal to 1. When it does, it shows runtime error and therefore I am unable to submit this exercise. Can someone please tell me where did I do wrong?

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

int main(int argc, string argv[])
{
    string key = (argv[1]);
    int keylen = strlen(key);

    //make sure the the key is entered and is 1 word
    if (argc != 2)
    {
        printf("Error. Try Again. \n");
        return 1;
    }


    for (int i = 0, n = strlen(key); i < n; i++)
    {
        if (!isalpha(key[i]))
        {
            printf("Error. Try Again.\n");
            return 1;
        }
    }

    //get plaintext from user
    string text = get_string("Plaintext: ");
    printf("ciphertext: ");

    //create integer for key loop

    for (int i = 0, j = 0, textlen = strlen(text); i < textlen; i++, j++)
    {
        if (isalpha(text[i]))
        {
            //check if each character is lowercase
            if islower(text[i])
            {
                printf("%c", 'a' + ((text[i] - 'a') + (key[i % keylen] - 'a')) % 26);
            }
            else if (isupper(text[i]))
            {
                printf("%c", 'A' + ((text[i] - 'A') + (key[i % keylen] - 'A')) % 26);
            }
        }
        // returns all non-alphabet value
        else
        {
            printf("%c", text[i]);
        }

    }

    printf("\n");
    return 0;

}
0

When argc == 1, it fails because the code is trying to assign argv[1] to key when argv[1] doesn't exist. In other words, the program is executed without a key parameter.

string key = (argv[1]);

The code needs to check that argc == 2 first, in order to catch that condition.

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

  • I have tried adding an else condition after the if { argc !=2 } statement and moving all the remaining code into it. I have also tried using another if loop which the condition is that argc == 2. In both ways, the result becomes incorrect. So is there any other way of checking argc == 2 and still getting the correct result? – jsyf May 8 '19 at 19:25
  • You're overthinking it. Undo what you just did and just move the if statement up to the top of the program. This fixes the described problem. If there are other issues (and there are), that's another matter and those isssues have to be dealt with. If you have new issues, please open another question. – Cliff B May 8 '19 at 20:18
  • Thank you for your help. As you have suggested, when this one problem is solved, other problems do appear... But thank you anyway for this suggestion! – jsyf May 9 '19 at 6:10

You must log in to answer this question.

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