0

I have almost completed the vigenère pset2 bar checking that each char in the keyword is an alphabetic character. My code below exits the program as soon as it reaches the first branch in the if statement. Here, argv[1] is the keyword.

for (int k = 0; k < strlen(argv[1]); k++)
    {
        if (isalpha(argv[1][k]))
        {
            return 0;
        }
        else
        {
            printf("Please try again.\n");
            return 1;
        }
    }
1

You've almost got it! Think about the code for a minute. Anytime a return statement is executed, it terminates what is going on. If it's in a function, it returns to the code that called the function. If it is in main, it terminates the program and returns to the operating system.

Now, look at the code posted. It is an if/else sequence with an return in both branches. That means that the program is going to terminate no matter what. (I'm assuming this is in main.) That's a real problem.

Let's think about both the solution and what you're really trying to do. The program spec says to verify that all the chars are letters, but in reality, it's saying this: If all are letters, proceed (i.e. do nothing now, but continue with the program when the check is finished), but if any one char is not a letter, terminate.

Simplified, that means to check for a non-alpha and, if found, exit. So, all it really needs to do is:

for(...;...;...)
{
    if(! isalpha(...)
    {
        // print message and return 1
    }
}

Since nothing needs to be done in this loop when the char is an alpha, there's no need for code to cover that event.

Like I said, you almost had it. You just had some extras that you didn't need! Bonus points for trying to cover all the bases, but sometimes, that's not necessary. ;-)

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

You must log in to answer this question.

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