0

I think the problem is in the loops, probably something wrong with my ASCII math, I've tried everything I could but I can't comeup with a solution in 9 hours of trying, I need help...

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

int main(int argc, string argv[])
{
    /* Program that encrypts user message, through Vigenere's Cypher
     * using the desired keyword
     */

    // Input Validation
    if (argc == 2)
    {
        string keyword = argv[1];
        int keywordLenght = strlen(keyword);
        for (int i = 0 ; i < keywordLenght ; i++)
        {
            if (!isalpha(keyword[i]))
            {
                printf("Invalid Keyword.\n");
                return 2;
            }
        }
        // Gets the text to be enciphered
        string text = GetString();
        // Enciphers the text using the desired key
        int textLenght = strlen(text);
        int key;
        for (int n = 0 ; n < textLenght ; n++)
        {
            if (isalpha(text[n]))
            {
                if (isupper(text[n]))
                {
                    key = toupper(keyword[n % keywordLenght]);
                    text[n] = text[n] + ('A' - key) % 26;
                }
                else
                {
                    key = tolower(keyword[n % keywordLenght]);
                    text[n] = text[n] + ('a' - key) % 26;
                }
            }
            else
            text[n] = text[n];
        }
        printf("%s\n", text);
    }
    else 
    {
        printf("Invalid Input.\n");
        return 1;
    }
}
1

I see two problems. First, the indexes for tracking the char to use from the key string and the plain text string are independent. You can't use the same index ( n ) on both. The key only advances to the next char when a letter is processed in the plain text. When you process a non-alpha, the index on the key does not change.

Next, the encoding formula that you are using doesn't work. Both the plain text and the key need to be transformed to numbers between 0 and 25 before the %26 can be applied. After that, the result needs to be transformed back to an ASCII number. I'll leave it to you to figure out how, but a review of the class videos would be useful.

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

1
  • I now love you sir, and FYI it's working now, thank you very much for your help. s2 Dec 9 '15 at 22:21

You must log in to answer this question.

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