First of all, this is why it's important to get the indentation aligned correctly so you can see what goes with what. Here's the corrected indentation.
int main(int argc, string argv[])
{
if (argc != 2)
{
printf("Usage: ./caesar key\n");
}
else if (argc == 2)
{
for (int i = 0; i < strlen(argv[1]); i++)
{
if (isdigit(argv[1][i]) == 0)
{
printf("Usage: ./caesar key\n");
}
}
else
{
printf("Sucess\n");
}
} // else clause should follow this line
}
The problem is that the else statement is not paired to any if or else if statement, because of the layout of the curly braces. You would need to move the else or a curly brace to get it properly paired. If you were to move the else clause below the curly brace that I marked, it would work.
Having said that, this whole setup is not a best practice. Here's why. First of all, there should be return statements following each printf (error message). Once that's done, all of the elseif and else statements become unnecessary.
The idea is NOT to surround the entire code that follows (which is where you're heading, and a common error by new programmers.) The reason not to do so is that it leads to confusion when the code is inevitably modified later. Someone, or even you, may not be familiar with the code and could miss that there's a closing curly brace at the end of the program that's connected to an else near the beginning.
Instead, the best practice is to do the tests for correct input, but contain those tests in a few lines of code, with no dependencies later. To explain with an example, you'd want to do this:
if (argc != 2)
{
printf("Usage: ./caesar key\n");
return 1;
}
for (int i = 0; i < strlen(argv[1]); i++)
{
if (isdigit(argv[1][i]) == 0)
{
printf("Usage: ./caesar key\n");
return 2;
}
}
printf("Sucess\n");
// the rest of the code can follow with no dependence on the earlier tests,
// and no closing curly brace at the end. The code above is decoupled from all that follows.
If you study this code, you'll note a couple things. Each time something is encountered that results in printing an error message, it's followed by a return that terminates the program immediately. Because of the return statements, the code that follows will never run if the prior error is detected. That eliminates the need for an else or if else construct. It also decouples the following code from the test conditions.
If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)
else if
block is missing a closing}