Spiros said:
Ok , write a programme which eliminates the blanks from
the end of every line in its standard input and prints the
result on standard output.
Good idea.
There are some idioms in C which you can re-use over and over every time
you see a problem like this.
Here is one that copies each character from standard input to standard
output:
First you define an int variable to hold the result of getchar. That
will be a value from 0 to UCHAR_MAX if successful, and a negative value
called EOF if unsuccessful. Don't try to use a char variable for this.
int ch;
Then you start a loop. Each time through the loop, there is a complex
expression that is evaluated. First, the getchar function is called and
the result is stored in ch. Then the result is compared against the
constant EOF. The loop continues while the value returned is not EOF.
while( (ch = getchar()) != EOF )
{
/* Inside the loop, for each character, you must output it */
putchar(ch);
}
And make sure to remember to end your main function with
return 0;
Here's the complete program:
#include <stdio.h>
int main(void)
{
int ch;
while((ch = getchar()) != EOF)
{
putchar(ch);
}
return 0;
}
Now think about how to modify this basic copying program, to remove any
spaces from the end of lines.
You can test whether you have read a space, a newline character, or some
other type like this:
if(ch == ' ')
{
/* do something */
}
else if(ch == '\n')
{
/* do something else */
}
else
{
/* do something different */
}
There is a tricky part though, as you will be reading the space
characters before the newline comes in. You don't know how many space
characters will come in. You might read 10 of them and then find there
is a non-space character. In that case the 10 spaces you read were not
at the end of the line but in the middle, and they must be preserved in
the output.
I would introduce a new variable, to keep track of how many spaces have
been read. When I read a space, I will just increment the counter, but
not actually output anything. When I read a newline, I will reset the
counter to zero but not output anything except the newline. But when I
read something that is neither a space nor a newline, I must print some
spaces, according to the current value of the counter. I will then reset
the counter and print the actual character that was read.
Can you implement this in C? You will need to add one or two new
variables and another loop inside.
Or perhaps you can think of an even better way to solve the problem?