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


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

   string plain;
   string key;

     // Making sure that the command line only accepts two arguments and is a keyword.

    if ((argc != 2) && (argc != isalpha(argc)))

    // Prints out an error message if the user inputs invalid information.
    {
        printf("missing command-line argument\n");
        return 1;
    }

    else

{
    // Getting the plaintext and the key.


    printf("plaintext:");

    plain = GetString();

    // Key

    key = argv[1];

    for (int j = 0, len2 = strlen(key); j < len2; j++)

    {

    for (int i = 0, len = strlen(plain); i < len; i++)
    {
        if (isalpha (plain[i]))
        {
            if (isupper (plain[i]))
            {
                printf("%c", ((plain[i] + key[j]) - 65));
            }


            if (islower (plain[i]))
            {

                printf("%c", (((plain[i] + key[j]) - 97) %26) + 97);

            }

         }

            else
            {
                printf("%c", (plain[i]));
            }

    }

    }

    }   

    printf("\n");
   return 0;
}
2

2 Answers 2

0

Your for loops are causing you problems. I've commented out the first one and added a j variable which increments every time a isalpha is passed. So now your algorithm is outputting the correct number of characters. But its not ciphering them correctly. You need to use % to wrap around your iteration of the keyword. Watch Zamyla's walkthrough for an explanation.
http://docs.cs50.net/problems/vigenere/vigenere.html

// for (int j = 0, len2 = strlen(key); j < len2; j++)
// {
int j = 0;
for (int i = 0, len = strlen(plain); i < len; i++)
{
    if (isalpha (plain[i]))
    {
        if (isupper (plain[i]))
        {
            printf("%c", ((plain[i] + key[j]) - 65));
        }


        if (islower (plain[i]))
        {

            printf("%c", (((plain[i] + key[j]) - 97) %26) + 97);

        }
        j++;
     }

        else
        {
            printf("%c", (plain[i]));
        }

}
0

There's one more thing to notice in your code which is related to the check for alphabetical arguments :

 if ((argc != 2) && (argc != isalpha(argc)))

// Prints out an error message if the user inputs invalid information.
{
    printf("missing command-line argument\n");
    return 1;
}

Now, the error here is that argc is storing an integer value and isalpha checks that a charachter is alphabetical or not . isalpha function can be used here with argv[1] string to iterate over each charachter to check if it's alphabetical or not. This function returns a boolean value (0/1) depending upon if the condition is false or true and this can be used to execute further statement. Hope that helps! Happy coding!

You must log in to answer this question.

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