Hello guys,
As a beginner i have some problems with understanding k&r exercises. i came across the exercise: Write a program to remove all trailing blanks and tabs from each line of input, and to delete entirely blank lines.
What is a trailing blank? when i run the code and put some spaces and tabs in the input, nothing seems changed in the output. there's written somewhere: advance(head)==tail, how is this case possible? if i put "space" 3 times, head=3 and then if i put some letters like"abc", tail=3 and blank[0], blank[1], blank[2] will be printed which are "spaces". How is this removing? the same goes if i put spaces after the letters. The soluton to this which i found is here:
Code:
#include <stdio.h>#include <stdlib.h>
#define MAXQUEUE 1001
int advance(int pointer)
{
if (pointer < MAXQUEUE - 1)
return pointer + 1;
else
return 0;
}
int main(void)
{
char blank[MAXQUEUE];
int head, tail;
int nonspace;
int retval;
int c;
retval = nonspace = head = tail = 0;
while ((c = getchar()) != EOF) {
if (c == '\n') {
head = tail = 0;
if (nonspace)
putchar('\n');
nonspace = 0;
}
else if (c == ' ' || c == '\t') {
if (advance(head) == tail) {
putchar(blank[tail]);
tail = advance(tail);
nonspace = 1;
retval = EXIT_FAILURE;
}
blank[head] = c;
head = advance(head);
}
else {
while (head != tail) {
putchar(blank[tail]);
tail = advance(tail);
}
putchar(c);
nonspace = 1;
}
}
return retval;
}