Search code examples
cwhitespacedetectiongetchar

Detect if space is pressed 3 times?


In my program I need to detect if the spacebar is pressed 3 times and then replace it whit a \n.

I am using getchar for getting my input and detecting one space is no problem but if I enter 3 spaces to check it does not work. Any help is very appreciated

This is my code so far witch works perfectly fine if I only check one spacebar but if I enter 3 of the it will not detect it

if (c == ' ')
{
putchar('\n');
}

Solution

  • You can count the number of consecutive spaces. Something like:

    int c;
    int spaces = 0;
    while((c = getchar()) != EOF)
    {
        if (c == ' ')
        {
            ++spaces;
            if (spaces == 3)
            {
                putchar('\n');
                spaces = 0;
            }
        }
        else
        {
            spaces = 0;
        }
    }