Search code examples
cwhile-loopcs50c-stringscontinue

(cs50)not getting output for the given code. can anyone please check this out?


my code counts the number of letters from the given string(excluding white space). cs50.h is a library which consists of get_string() function which takes input from user. the code is compiling but when i give an input which has more than one word, it stops working(doesn't give me anything).can anyone please tell why?(i am using c language)

#include <cs50.h>
#include <stdio.h>
#include <ctype.h>

int count_letters(string text);

int main(void)
{
    string input = get_string("Text: ");
    int letters = count_letters(input);
    printf("%i\n",letters);
}

int count_letters(string text)
{
    int i = 0;
    while(text[i] != '\0')
    {
        if(isspace(text[i]))
            continue;

        i++;
    }
    return i;
}

Solution

  • You have an infinite while loop when the entered string contains a white space character

    int count_letters(string text)
    {
        int i = 0;
        while(text[i] != '\0')
        {
    
            if(isspace(text[i]))
                continue;
    
            i++;
        }
        return i;
    }
    

    because when a white space character is encountered the variable i is not incremented due to the continue statement.

    Rewrite the function for example like

    int count_letters(string text)
    {
        int count = 0;
    
        for ( ; *text != '\0'; ++text )
        {
            if ( !isspace( ( unsigned char )*text ) )
            {
                ++count;
            }
        }
    
        return count;
    }
    

    Pay attention to that it will be much better if instead of the typedef name string as the parameter type specifier you will use the specifier const char * as for example

    int count_letters( const char *text);
    

    because the passed string is not changed within the function.

    And instead of the return type int it is better to use the type size_t.

    So the function can be declared and defined like

    size_t count_letters( const char *text )
    {
        size_t count = 0;
    
        for ( ; *text != '\0'; ++text )
        {
            if ( !isspace( ( unsigned char )*text ) )
            {
                ++count;
            }
        }
    
        return count;
    }
    

    And in main the function is called like

    char *input = get_string("Text: ");
    size_t letters = count_letters(input);
    printf("%zu\n",letters);