How to use an isalpha result to initiate an if statement?

3.5k Views Asked by At

Okay, so I have a for loop that checks through every letter of a string to make sure that the string is made entirely of alphabetical characters before moving on to the next stage of the program.

However, I am having trouble with my if statement that is supposed to run if the "isalpha" function comes back false.

string keyword = argv[1];
for (int i = 0; i < strlen(keyword); i++)
{
    char letter = keyword[i];
    if (isalpha(letter) = false)
    {
        printf("Only use alphabetical characters in your key\n");
        return 1;
    }

I am getting the error:

error: expression is not assignable if (isalpha(letter) = false)

How can I get an if statement that initiates due to a isalpha being false?

How is the following wrong?

if (isalpha(letter) = false)
2

There are 2 best solutions below

0
On

How is the following wrong?

if (isalpha(letter) = false)

Well, it's an assignment! = is used to assign a value, and you can't assign a value to a function call (for hopefully obvious reasons)

To compare values, you use the == operator in C.

That said, checking for equality with == is not necessary at all when you already have boolean values. Just write:

if (!isalpha(letter))
3
On

You made a typo: if (isalpha(letter) = false) is not a comparison, but an assignment. You should instead write:

if (isalpha(letter) == false)

A more common way to write this is with the ! operator:

if (!isalpha(letter))

Note however that isalpha() has undefined behavior for negative values different from EOF, and if the char type is signed, the value if letter can be negative. This problem is corrected with a cast:

if (!isalpha((unsigned char)letter))