0

Week 2's switch.c example really appealed to me--found it very clean and easy to read. I did Vigenere's using for loops and if statements and tried to rewrite it using a switch. My code doesn't even compile. Checked the man pages on toupper and based on Clang's output, my guess is it's because the function returns an int? Really appreciate any help.

// prompts user for text to encrypt
printf("plaintext:");
string plain = get_string();

// checks user entered valid string
if (plain != NULL)
{
    printf("ciphertext:");

    // iterates thru plain one char at a time
    for (int i = 0, j = 0, pl = strlen(plain), kl = strlen(key); i < pl; i++)
    {
        // checks if char in string is alphabetic letter
        if (isalpha(plain[i]))
        {

            switch (plain[i])
                {
                    case (isupper):
                        // makes plain alphabetic, adds key[j], changes to ascii
                        char cipher = (((plain[i] - 'A') + (toupper(key[j % kl]) - 'A')) % 26) + 'A';
                        printf("%c", cipher);
                        j++;
                        break;

                    case (islower):
                        // changes plain from ascii to alphabetic, adds key[j], changes back
                        char cipher = (((plain[i] - 'a') + (tolower(key[j % kl]) - 'a')) % 26) + 'a';
                        printf("%c", cipher);
                        j++;
                        break;

                    default:
                        printf("%c", plain[i]);
                }

        }

    }    

}

1 Answer 1

0

What follows the word "case" should be one of the possible values of the variable in your switch statement, (plain[i]).

case (isupper) doesn't mean anything because isupper is a name of a function, not a possible value of (plain[i]).

You can try rewriting it like this:

bool uppercase = isupper(plain[i]);
switch (uppercase)
{
case true { do some stuff }

case false { do other stuff }

default { stuff }
}
1
  • Great. Thanks so much for the example.
    – Lindsey
    Apr 1, 2017 at 6:13

You must log in to answer this question.

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