solutions/The C Programming Language/1.21.c

62 lines
854 B
C
Raw Normal View History

2024-05-02 07:15:30 -04:00
#include <stdio.h>
// replacing empty strings consisting of only spaces
// to tabs and spaces so it keeps initial indentation
2024-05-02 07:15:30 -04:00
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 - 1;
}
void entab(char to[], char from[], int columns)
{
int spaces_counter = 0;
int from_i = 0;
int to_i = 0;
while (from[from_i] != '\0')
{
++spaces_counter;
++from_i;
if (spaces_counter == columns)
{
to[to_i] = '\t';
++to_i;
spaces_counter = 0;
}
}
while (spaces_counter > 0)
{
to[to_i] = '_';
++to_i;
--spaces_counter;
}
to[to_i] = '\0';
}
main()
{
int size = 500;
char from[size];
char to[size];
while (1)
{
_getline(from, size);
entab(to, from, 4);
printf("%s\n", to);
}
}