Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use putchar to "squeeze" characters (Ansi-C)

Tags:

c

i was wondering if i could get some help for my code. I put some partial code below

/*reads char by char til EOF*/
while((c = getchar()) != EOF)
{

    if(c == '\t')
    {
        putchar(' ');
    }
    else if(c == ' ')
    {
        putchar('d');
    }
    else
    {
        putchar(c);
    }
}

What I am trying to do right now is squeeze space characters entered by the user. So if the user puts in:

a[SPACE][SPACE][SPACE][SPACE][SPACE][SPACE][SPACE][SPACE]a

The output should be just

a[SPACE]a

Right now i have it set up that it replaces all spaces for d's for testing purposes. How would I change my code so that it just prints out 1 space instead of all the spaces the user puts in.

Thanks for any help in advance.

like image 295
user798774 Avatar asked Nov 17 '25 14:11

user798774


2 Answers

Just keep a whitespace flag:

int lastWasSpace = 0;
while((c = getchar()) != EOF) {
    if(c == '\t' || c == ' ') { // you could also use isspace()
        if(!lastWasSpace) {
            lastWasSpace = 1;
            putchar(c);
        }
    } else {
        lastWasSpace = 0;
    }
}
like image 162
Ry- Avatar answered Nov 20 '25 04:11

Ry-


One solution:

/*reads char by char til EOF*/
int hasspace = 0;

while((c = getchar()) != EOF)
{
    if (isspace(c))
        hasspace = 1;
    }
    else
    {
        if (hasspace)
        {
            hasspace = 0;
            putchar(' ');
        }
        putchar(c);
    }     
}
like image 39
Richard Pennington Avatar answered Nov 20 '25 03:11

Richard Pennington



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!