Hello everyone.
I'm trying to understand why my program wont work correctly.
At this point I'm blocked.
Exercise asking:
"Write a program to remove trailing blanks and tabs from each line of input, and to delete entirely blank lines."
What I'm observing is:
If I put some characters followed by trailing blanks (or tabs) I get a nice result (or I think so?).
But when I'm writing only characters the result is always a line with minus one character.
My system: Debian 64bit as virtual machine.
Here is the code:
Code:
#include <stdio.h>
#define MAXLINE 1000 /* maximum input line size */
int remove_blanks_from_input(char line[], int maxline);
/* print longest input line */
int main()
{
char line[MAXLINE];
int status;
while ((status = remove_blanks_from_input(line, MAXLINE)) > 0) {
if (status != 1) {
printf("%s", line);
}
}
if (status < -1)
printf("%s", line);
if (status == 0) printf("Check the test conditions in 'remove_blanks_from_input' funtion.\n");
return 0;
}
/* remove_blanks_from_input: remove trailing blanks and tabs and delete entirely blank lines */
int remove_blanks_from_input(char s[], int lim)
{
int c, i, j, blanks_count = 0;
for (i = 0; (c = getchar()) != EOF && c != '\n'; ++i) {
// use a limited size buffer character array s[]. If size of the input line is bigger that buffer_size - 1 stop copying. Last index is for null character.
if (i < lim - 1) {
j = i;
s[j] = c;
}
// count current blanks string
if (c == ' ' || c == '\t') ++blanks_count;
else blanks_count = 0;
}
// If number of characters in the incoming line (not including '\n') is equal to number of blanks encountered, consider line empty.
//
if ((i - blanks_count) == 0 && c == EOF)
return -1;
else if ((i - blanks_count) == 0)
return 1;
// If number of blanks in current blanks string is less than the length of the incoming chracter array => there is some printable characters in it.
else if ((i - blanks_count) <= j && c == EOF) {
s[i - blanks_count + 1] = '\0';
return -2;
}
else if ((i - blanks_count) <= j) {
if (j < lim - 2) {
s[i - blanks_count + 1] = '\n';
s[i - blanks_count + 2] = '\0';
return 2;
}
else {
// the element at index 'lim - 2' will be lost (replaced by '\n')
s[i - blanks_count] = '\n';
s[i - blanks_count + 1] = '\0';
return 2;
}
}
// If length of the incoming character array minus length of the current blanks string is >= lenght of the buffer character array minus 1.
else if ((i - blanks_count) > j && c == EOF) {
s[++j] = '\0';
return -2;
}
else if ((i - blanks_count) > j) {
// the elemnts at indexes 'lim - 2' including and further will be lost
s[j] = '\n';
s[++j] = '\0';
return 2;
}
else return 0; // if status code is 0. Probably some of the test conditions are wrong
}
Thanks for your answer. I hope code is clear enough to understand.