HiveBrain v1.2.0
Get Started
← Back to all entries
patterncModerate

Replacing each string of one or more blanks by a single blank

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
eachblanksmoreblankonesinglereplacingstring

Problem

K&R 1.9 exercise:


Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank.

Is this correct and proper code? Could I have put c and inspace on a single line?

#include 

int main(void)
{
    /*initializes c and inspace. */
    int c;
    int inspace;

    /*sets inspace = 0*/
    inspace = 0;

    while((c = getchar()) != EOF)
    {
        if(c == ' ')
        {
            if(inspace ==0)
            {
                inspace = 1;
                putchar(c);
            }
        }

        if(c != ' ')
        {
            inspace = 0;
            putchar(c);
        }
    }

    return 0;
}


I am using the latest Ubuntu distro 64 bit.

Solution

Looks fine to me. But I would replace

if (inspace == 0)


with

if (!inspace)


for stylistic reasons. And

if (c != ' ')


with

else


because there is no need to compare c again: you already know it isn't equal to a space because of the first if statement.

Also the code inside {...} after main should be indented over.

Code Snippets

if (inspace == 0)
if (!inspace)
if (c != ' ')

Context

StackExchange Code Review Q#9287, answer score: 10

Revisions (0)

No revisions yet.