Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 30 additions & 9 deletions chapter_1/exercise_1_18/trailing_blanks.c
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
#define MAXLINE 1000

int get_line(char line[], int max_line_len);
void remove_trailing_blanks(char line[], int length);
int remove_trailing_blanks(char line[], int length);

int main(void)
{
Expand All @@ -12,8 +12,12 @@ int main(void)

while ((len = get_line(line, MAXLINE)) > 0)
{
remove_trailing_blanks(line, len);
printf("%s", line);
len = remove_trailing_blanks(line, len);

if (len > 1 || line[0] != '\n')
{
printf("%s", line);
}
}

return 0;
Expand All @@ -39,13 +43,30 @@ int get_line(char line[], int max_line_len)
return i;
}

void remove_trailing_blanks(char line[], int length)
#define HAS_NEWLINE 1
#define NO_NEWLINE 0

int remove_trailing_blanks(char line[], int length)
{
int i;
int i, has_newline;

has_newline = NO_NEWLINE;

for (i = length - 1; i >= 0 && (line[i] == '\n' || line[i] == ' ' || line[i] == '\t'); --i)
{
if (line[i] == '\n')
{
has_newline = HAS_NEWLINE;
}
}

for (i = length - 2; line[i] == ' ' || line[i] == '\t'; --i)
;
if (has_newline == HAS_NEWLINE)
{
line[i + 1] = '\n';
line[i + 2] = '\0';
return i + 2;
}

line[i + 1] = '\n';
line[i + 2] = '\0';
line[i + 1] = '\0';
return i + 1;
}