0
#include <cs50.h>
#include <stdio.h>
#include <ctype.h>
#include <string.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;
    char l = text[i];
    int len = strlen(text);
    do{
        i++;
    }while(isspace(text[i]) == 0 || l != '\0');

    return i;
}

I wrote a code which counts number of letters in a sentence(excluding white space).but when I run it, its showing Segmentation fault (core dumped). can anyone help me where i went wrong?

1 Answer 1

1

The count_letters() function has a couple of flaws. First, the seg fault. The code sets l = the first letter before the start of the loop. The problem with this is that l is never updated inside the loop. It will always be the first char in the string. Assuming that the first char is not '\0', the test for l != '\0' will always be true. If there are no spaces (see below), then this causes an infinite loop. The code is seg faulting because it's gone way past the end of the string. Otherwise, it would just go on forever. l needs to be updated inside the loop for every pass.

Second, if there is a space, the loop will terminate. Any later chars in the string won't be counted. Hint: the IF statement is your friend.

BTW, how does the code handle characters that are not letters, spaces or blanks?

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

1
  • Yahh...got it thanks.. i made l update for every pass and used isalpha() function from <ctype.h> library to handle characters that are not letters..(and i used IF statement as u suggested) Commented Aug 23, 2022 at 17:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .