Search code examples
cinfinite-loopcountingcs50

Count all characters in a string but spaces


I have so far, in my C code where it counts everything in a user given string, however, I only want it to count letters.

Whenever I try and take out or change the spaces counter my code ends up breaking and forces me to manually stop it.

I would like to use the spaces sometime later as a method to count words but I'd rather try and get the letters done first.

What I mean by it breaks is that the code will proceed to infinitely do nothing. I found this out when instead of putting something down I had it printed and it constantly repeated what was given with no stopping.

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

int main(void)
{   
    string s = get_string("Text: ");
    int n = 0;

    while (s[n] != '\0')
    {
        if (isalpha(s[n])) //counts letters
        {
            n++;
        }
        else
        {

        }
    }

I would like to try and keep the code similar, but if its easier, a different way.

Also I would like to keep it to where it will be able to process a string given by the user.


Solution

  • If you look closely at the cycle:

    while (s[n] != '\0')
    {
        if (isalpha(s[n])) //counts letters
        {
            n++;
        }
    }
    

    you will notice that when s[n] is not alpha, n is not incremented, so you're stuck in an infinite loop.

    The counter and the iterator should be different variables:

    int count = 0;
    //...
    while (s[n] != '\0')
    {
        if (isalpha(s[n])) 
        {
            count++; //counts letters
        }
        n++; //increment iterator
    }