0

when i use isString function or any function which containing "isalpha" function. My code provide missing output. When i remove isString function it works well. But i don't understand relationship between isString function and the rest of the code.

    $ ./vigenere abc
    plaintext: hello
    ciphertext: hfnl

I have the following relevant code for encrypting in the Vigenere cipher:

    bool isString(string world);
    int shift(char c);
    
    
    int main(int argc, string argv[])
    {
        
        if (argc != 2 || isString(argv[1]) // When i remove "isString" it works well.
        {
            printf("Usage: ./vigenere keyword\n");
            return 1;
        }
        else
        {
            char key;
            
            string plaintext = get_string("plaintext: ");
            char chiphertext[strlen(plaintext)];
           
            for(int i = 0, j = 0; i < strlen(plaintext); i++)
            {
                
                if (j >= strlen(argv[1]))
                {
                    
                    j = 0;
                    
                }
                key = argv[1][j];
                //check lowercase letter
                if(plaintext[i] >= 97 && plaintext[i] <= 122)
                {
                    chiphertext[i] =  (((plaintext[i] - 97) + shift(key)) % 26) + 97;
                    j++;
                
                }
                else if(plaintext[i] >= 65 && plaintext[i] <= 90)
                {
                    chiphertext[i] =  (((plaintext[i] - 65) + shift(key)) % 26) + 65;
                    j++;
                }
                else
                {
                    chiphertext[i] = plaintext[i];
                }
                     
            }
            printf("ciphertext: %s\n",chiphertext);
            return 0; 
                
        }
    
    }
    
    
    
    int shift(char c)
    {
        int key;
        if(c >= 97 && c <= 122)
        {
            key = ((c - 97) % 26);
        }
        if(c >= 65 && c <= 90)
        {
            key = ((c -65) %26);
            
        }
        //printf("%i\n",key);
        return key;
    }
    
    bool isString(string world)
    {
        for(int i = 0; i < strlen(world); i++)
        {
            if (!isalpha(world[i]))
            {
                return false;
            }
        }
        return true;
    }
0

Every char array, including chiphertext[strlen(plaintext)] has last char equal to zerobyte '\0'. So if you want strlen(plaintext) alphabetical chars declare one char more: chiphertext[strlen(plaintext)+1]

You must log in to answer this question.

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