So, I just finished with my vigenere code but the output is different from the expected one. I'm posting my code and hope any of you guys finds my mistake and gives me a tip.

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

int main(int argc, string argv[])
    while(argc != 2)                    //yells at the user if more or less than 2 arguments
        printf("Enter a key.\n");
        return 1;

    string s = GetString();         //user gives input

    for(int i = 0, n = strlen(s); i < n; i++)       //goes through every character of that input
        if(isalpha(s[i]))               //checks if its a letter character
            if(isupper(s[i]))               //checks if its an uppercase letter
                int p = strlen(argv[1]);
                int f = i % p;               //synchronizes every character from the key with every character from the sentence
                char v = s[i] - 65;
                char a = (v + argv[1][f]) % 26;               //uses modulo, so that the output is only alphabetical
                char l = a + 65;
                printf("%c", l);                //prints the encrypted character                    

                    int p = strlen(argv[1]);                    //same process but for lowercase letter
                    int f = i % p;
                    char t = s[i] - 97;
                    char y = (t + argv[1][f]) % 26;
                    char u = y + 97;
                    printf("%c", u);
            printf("%c", s[i]);                 //prints every other non-alphabetical character
  • I had the same issue. The problem with using the loop counter (i) to figure out (f) is that it is incremented even on non-alpha's, which per the pset's specs is not the behaviour you want. You need to figure out a way to keep track of your key so that it is incremented ONLY when you encounter an alphabetic character.
    – dLopez
    Aug 6 '16 at 15:00
  • But wouldn't the use of the "isalpha" function fix that because the loop wouldn't even start when there is a non-alpha character or am I missing something? Aug 6 '16 at 15:08
  • Not really, your loop is cycling through the plain text array, one char at a time. This progress is measured by the variable (i) which is incremented by one each time you complete a pass through the loop, even if your if(isalpha(s[i])) condition is not triggered, (i) will still be incremented by one.
    – dLopez
    Aug 6 '16 at 15:28
  • I think I got it and thought of a solution but now after I declared a variable to deal with the problem a strange error pops out. I'm going to edit the code and add the error as an to my post and hope that you'd once again help me with an explanation or a tip. Aug 6 '16 at 15:50
  • If you found a solution please post an answer and accept it so that this question is removed from the unanswered pool.
    – dLopez
    Aug 6 '16 at 18:38

You must log in to answer this question.

Browse other questions tagged .