solutions/The C Programming Language/1.18.c

56 lines
840 B
C
Raw Normal View History

2024-05-01 04:27:10 -04:00
#include <stdio.h>
#define MAXLINE 10
int _getline(char line[], int maxline);
void trim(char to[], char from[], int from_head);
// remove all extra spaces and tabs from tail of input
2024-05-01 04:27:10 -04:00
main()
{
char line[MAXLINE];
char trimmed[MAXLINE];
int head = _getline(line, MAXLINE);
trim(trimmed, line, head);
printf("[%s]\n", trimmed);
return 0;
}
int _getline(char s[], int lim)
{
int c, i, j;
for (i = 0; (c = getchar()) != '\n'; ++i)
{
if (i < lim - 1)
s[i] = c;
}
j = i;
if (j > lim - 1)
j = lim - 1;
s[j] = '\0';
return j;
}
void trim(char to[], char from[], int from_head)
{
int i;
int start_copying = 0;
for (i = from_head - 1; i >= 0; --i)
{
if (start_copying == 0 && from[i] != '\t' && from[i] != ' ')
{
to[i+1] = '\0';
start_copying = 1;
}
if (start_copying == 1)
to[i] = from[i];
}
}