Vince Vince - 1 year ago 45
C Question

Beginner level. Coding in C. Having trouble with "if else".

Can someone please help. Im new to programming and doing the cs50 course. The task is to scramble plain text based on a code word. The language is C and on linux.

I seem to have it all working but I am banging my head for the last 2 hours trying to fix the last error when compiling the program. The problem I am having is the bottom half of the program (after the //Cipher funtion bit)

This is the error:

viginere.c:39:5: error: expected expression
viginere.c:44:5: error: expected expression
2 errors generated.

I cant see what I have done wrong with this.

I have messed around with the {} in several different places but I dont think that is the problem as this program is a modified version of a program i made before and that one works, with the same layout (just different with a slightly different printf) What am I missing?

Heres my code:

int main (int argc, string argv[])
//change command line string to a number
int k = atoi(argv[1]);
string v = argv[1];

//check program command line was typed correctly
if (argc != 2 || k != 0)
printf("Restart program with keyword in command line (alphabetical characters only)\n");
return 1;

//Get Plain Text
printf("The keyword is set to %s.\nType in your plain text: ", argv[1]);
string s = GetString();

//Print Cipher
printf("Your cipher text = ");

//Set variables for mudulo on keyword
int codecount = strlen(argv[1]);
int c = 0;

//Cipher function (Errors are in this part)
for (int i = 0; i < strlen(s); i++)
//Cipher uppercase
if (isupper(s[i]))
printf("%c", (s[i] + v[c%codecount] - 65)%26 + 65);
//Else Cipher lowercase
if (islower(s[i]))
printf("%c", (s[i] + v[c%codecount] - 97)%26 + 97);
//Print all else as normal
printf("%c", s[i]);

Answer Source

Use curly brackets...

When there is more than one line to be executed as a result of an if(condition), each must be encapsulated with curly brackets.

    statement2();//without brackets this would not be executed

In the same way, if there are multiple lines that should be executed if and only if the if(condition) is false, they must also be surrounded with curly brackets starting after the else keyword.

    statement4();//without brackets, this would not be executed

There are different opinions on if curlys should be used for only single lines after if and else, but readability, maintainability and reliability are reasons enough to use curly brackets religiously.