patterncModerate
Replacing each string of one or more blanks by a single blank
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
I am using the latest Ubuntu distro 64 bit.
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
with
for stylistic reasons. And
with
because there is no need to compare
Also the code inside {...} after
if (inspace == 0)with
if (!inspace)for stylistic reasons. And
if (c != ' ')with
elsebecause 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.