This is my solution to exercise 1-21 of “The C Programming Language, 2nd Edition” by Kernighan and Ritchie.
#include <stdio.h>
#define TABSIZE 4 /* size of a tab stop */
/* replace strings of blanks with tabs and blanks */
int main()
{
int c, ns = 0;
while ((c = getchar()) != EOF)
if (c == ' ')
ns++;
else {
for (; ns >= TABSIZE; ns -= TABSIZE)
putchar('t');
for (; ns > 0; ns--)
putchar(' ');
putchar(c);
}
/* handle edge-case when file ends with spaces */
for (; ns >= TABSIZE; ns -= TABSIZE)
putchar('t');
for (; ns > 0; ns--)
putchar(' ');
return 0;
}
I figured out that spaces are omitted if the input ends with spaces near end of file.
My solution involves repetition of the for loops which I know is considered a bad practice. But I think creating a seperate function to handle spaces would be too extra to an otherwise simple solution.
I tried using preprocessor macros to hide this redundancy.
#include <stdio.h>
#define TABSIZE 4 /* size of a tab stop */
#define HANDLE_SPACES(count) { for (; ns >= TABSIZE; ns -= TABSIZE)
putchar('t');
for (; ns > 0; ns--)
putchar(' '); }
/* replace strings of blanks with tabs and blanks */
int main()
{
int c, ns = 0;
while ((c = getchar()) != EOF)
if (c == ' ')
ns++;
else {
HANDLE_SPACES(ns);
putchar(c);
}
/* handle edge-case when file ends with spaces */
HANDLE_SPACES(ns);
return 0;
}
Is this a bad programming practice? What is the best option in my case?
ToxicNinja is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.