I'm reading K&R's The C Programming Language and currently working on Exercise 1-12. The issue I'm facing isn't with completing the exercise itself, but with fixing a bug that has come up as a result of my code.
The code produces an unwanted blank line when encountering two or more spaces. I want to ensure that the output has no blank lines and that extra spaces are trimmed.
My solution.
#include <stdio.h>
int main(void)
{
int c;
while ((c = getchar()) != EOF)
{
if (c == ' ' || c == '\t')
{
printf("\n");
}
else
{
putchar(c);
}
}
}
Problematic output
bash >>> ./Exercises/ex12
hello everyone
hello
everyone
I tried solving it based on Ex 1-9 [2], but no luck.
#include <stdio.h>
#define PREVCHAR 'a'
int main(void)
{
int c, prevc = PREVCHAR;
while ((c = getchar()) != EOF)
{
if (c == ' ' && prevc == ' ')
{
printf("");
} else if (c == ' ' && prevc != ' ')
{
printf("\n");
} else
{
putchar(c);
prevc = c;
}
}
}
[1] = Write a program that prints its input one word per line.
[2] = Write a program to copy its input to its output, replacing each string of one or more blanks by a single blank.
I think you want to achieve the following output:
hello
everyone
The reason there is a blank line is that your algorithm just replaces each space/tab by a new line.
Your principal idea to simply check if the previous char was a space or a tab is correct.
The problem is, you only set prev
in case it is not a blank space.
Because of that, prev
will never be a space or a tab.
Furthermore, I suggest doing something like this:
#include <stdio.h>
int main(void)
{
int c;
bool previousWasBlank = false;
while ((c = getchar()) != EOF)
{
if (c == ' ' || c == '\t')
{
if (!previousWasBlank)
printf("\n");
previousWasBlank = true;
}
else
{
putchar(c);
previousWasBlank = false;
}
}
}