Good evening. I have the following exercise from K&R:
Write a program entab that replaces strings of blanks with the minimum number of tabs and blanks to achieve the same spacing. Use the same stops as for detab . When either a tab or a single blank would suffice to reach a tab stop, which should be given preference?
What can I do to fit the logic of numberOfBlanks, numberOfTabs and printBlanks inside the code? I mean, I tried to put it after the else but that didn't work. I got something like:
Sansa s t a r k
I thought I could get the sum of every occurrence of a white space and then print all blanks after a word.
Code:
#include <stdio.h>
#define MAX_BUFFER 1024
#define SPACE ' '
#define TAB '\t'
// gets a line
int getLine(char s[], int lim);
// calculates the number of spaces for a tab (a tab = 5 blanks)
int calculateNumberOfSpaces(int offset, int tabSize);
// calculates only the number of blanks
int numberOfBlanks(int whitespaces, int tabSize);
// calculates only the number of tabs
int numberOfTabs(int whitespaces, int tabSize);
// prints the amount of number of blanks and tabs
void printBlanks(int numberofblanks, int numberoftabs);
void printBlanks(int numberofblanks, int numberoftabs)
{
int i;
for(i = 0; i < numberoftabs; i++)
{
putchar('\t');
}
for(i = 0; i < numberofblanks; i++)
{
putchar(' ');
}
}
int numberOfBlanks(int whitespaces, int tabSize)
{
return whitespaces % tabSize;
}
int numberOfTabs(int whitespaces, int tabSize)
{
return whitespaces/tabSize;
}
int calculateNumberOfSpaces(int offset, int tabSize)
{
return tabSize - (offset % tabSize);
}
int getLine(char s[], int lim)
{
int c, i;
for(i = 0; i < lim - 1 && (c = getchar()) != EOF && c != '\n'; i++)
{
s[i] = c;
}
if(c == '\n')
{
s[i] = c;
++i;
}
s[i] = '\0';
return i;
}
int main()
{
/*
nw - number of white spaces
tabSize - amount of white spaces for tab
l - number of characters input
j - number of spaces for tab
nb - number of blanks only
nt - number of tabs only
*/
int i, nw, tabSize, l, j, k, nb, nt;
nt = nb = j = nw = i = 0;
tabSize = 5;
char buffer[MAX_BUFFER];
while(getLine(buffer, MAX_BUFFER) > 0)
{
for(i = 0, l = 0; buffer[i] != '\0'; i++)
{
if(buffer[i] == TAB)
{
j = calculateNumberOfSpaces(l, tabSize);
nw += j;
for(k = 0; k < j; k++)
{
l++;
}
}
else if(buffer[i] == SPACE)
{
++nw;
l++;
}
else {
putchar(buffer[i]);
l++;
}
/*
I don't know how to fit these functions
nb = numberOfBlanks(nw, tabSize);
nt = numberOfTabs(nw, tabSize);
printBlanks(nb, nt);
*/
}
}
return 0;
}