Trying to make a loop which counts letters but not spaces

171 Views Asked by At

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);
}
2

There are 2 best solutions below

3
On BEST ANSWER

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.

2
On

This record

s[i] (isalpha)

is incorrect and does not make a sense.

What you need is the following

size_t c = 0;

for ( size_t i = 0; s[i] != '\0'; i++ )
{
    if( isalpha( ( unsigned char )s[i] ) ) ++c;
}
printf("c = %zu\n", c );

Pay attention to that the function isalpha is declared in the header <ctype.h> that you have to include.