I tried to follow some advice and started reading C programming language book. In the book there are several exercise and end of each chapter.
I've just did the following exercise:
Write a program entab that replaces strings of blanks by the minimum number of tabs and blanks to achieve the same spacing. When either a tab or single blank would suffice to reach a stop tab, which would be given preference?
My solution to this problem was the following:
#include <stdio.h>
#include <stdlib.h>
int get_string(char string[], int index)
{
for(int position = 0; position < index; position++)
{
string[position] = getchar();
if(string[position] == '\n')
{
string[position] = '\0';
return position;
}
}
return index;
}
int get_spaces(char string[], int i)
{
int temp_i = 1;
while(string[i+1] == ' ')
{
temp_i++;
i++;
}
return temp_i;
}
int get_tabs(int spaces)
{
int tabs = 0;
tabs = spaces / 4;
return tabs;
}
void entab(char string[], int max_index)
{
int i = 0;
int spaces = 0;
int tabs = 0;
while(i <= max_index)
{
if(string[i] == '\t')
{
printf("\t");
i++;
}
else if(string[i] == ' ')
{
spaces = get_spaces(string, i);
i = i + spaces;
if(spaces == 4)
{
printf("\t");
spaces = 0;
}
else if (spaces < 4)
{
for(int i = 0; i < spaces; i++)
{
putchar(' ');
}
spaces = 0;
}
else
{
tabs = get_tabs(spaces);
// printf("%d", tabs);
spaces = spaces - (tabs*4);
// printf("%d", spaces);
for(int i = 0; i < tabs; i++)
printf("\t");
for(int i = 0; i < spaces; i++)
printf(" ");
tabs = 0;
spaces = 0;
}
}
else
{
putchar(string[i]);
i++;
}
}
}
int main()
{
char string[100] = "";
int howlong = get_string(string, 100);
entab(string, howlong);
return 0;
}
2 questions:
How is it possible that to reach a tab stop, a tab might be necessary (cit. When either a tab or single blank would suffice to reach a stop tab, which would be given preference?)? I mean to reach it you need a space, so you can't prefer one or the other, it 2 different cases. Or not?
I presume is not possible to do it directly of the 1st while loop without storing it in an array? or is it?
I'm pretty new to C programming, and programming in general so don't over estimate my capacities, I presume you can see that I'm not good at it, I'm trying to learn.
I dont know how to shrink the program down. It seems like an easy task yet I dont know how to address the problem.
and I think it doesn't work properly.
EDIT:
I HAVE REWROTE EVERYTHING. IM SURE ITS WORKING BUT DONT KNOW WHY IT PRINTS MORE SPACES, WHERE ARE THIS SPACES COMING FROM
The point is to reduce the size of the output. Since spaces and tabs are the same size, it doesn't matter. So use whichever you want.
No array is necessary. It's just a question of tracking three variables:
Algorithm
(Supports space, tab and LF as control characters.)
Read a character.
If EOF has been reached,
If the character is a LF,
Else,