Search code examples
cincrementisalpha

Trying to make a loop which counts letters but not spaces


I am trying to construct a simple programme which counts the number of letters in a user's input. My idea was to use a for loop which would loop for each letter in a string, increment a counter, and return the final counter total at the end. However, I do not want the programme to count spaces- I attempted to use the isalpha function to do this- but I seem to be formatting it incorrectly. Also, the way I tried to make the counter NOT increment for a space was with c = c, however, this also seems to be incorrect. Here is the code I have written so far:

int c = 0;

int main(void)
{
    string s = get_string("Input:  ");
    printf("Output: ");
    for (int i = 0; i < strlen(s); i++)
    {
    if( s[i] (isalpha))
        {
        c++;
        }
    else
        {
        c = c;
        }
    }
    printf("%i\n", c);
}

Solution

  • isalpha is effectively a function call. (It is a function call or a function-like macro.) A function call is written as name(), name(argument), or name(argument,…) according to whether it is passing zero, one, or more arguments. isalpha takes a single argument. That argument should be an unsigned char value. So you can call it as isalpha((unsigned char) s[i]). Your if statement should look like:

    if (isalpha((unsigned char) s[i]))
    

    Your program should also contain #include <ctype.h> to include the header that declares isalpha.