I am trying to write a program to insert spaces between words to fit a column, for example:
- You read in a line of text, eg:
Good morning how are you?
- You read in the width of the column, eg:
40
. - Then I have counted how many spaces there are in this text (4).
- Now I need to distribute the remaining spaces in between these words so the length of the text is 40.
For example:
Good morning how are you?
1234567890123456789012345678901234567890
My problem comes when I try to insert the spaces in between words as I don't know how to do this. This is what I have so far.
#include <stdio.h>
#include <string.h>
char text[65], spaces[50], ch;
int i, remainder, spacesr, count, column, length, distribution;
int main(){
i = 0;
count = 0;
printf("Please enter a line of text: ");
while(ch != '\n')
{
ch = getchar();
text[i]=ch;
i++;
}
text[i]='\0';
printf("Text: %s",text);
printf ("Please enter the width of the column: ");
scanf ("%d", &column);
for (i = 0; text[i] != '\0'; i++) {
if (text[i] == ' ') {
count++;
}
}
length = strlen(text);
spacesr = column - length;
distribution = spacesr / count;
remainder = spacesr % count;
if (length > column) {
printf ("ERROR: Length of text exceeds column width.");
}
}
I have calculated the amount of spaces in the read in text, then calculated the amount of spaces I would have remaining, then divided that by the amount of spaces to determine how many spaces I need to put between each word. The remainder of these spaces will be distributed evenly after the main spaces have been entered.
What do you mean by main spaces?
Basically I want to fit the phrase "Good morning how are you?" to a column 40 characters wide by adding spaces between words. Is it possible to do something like this:
for (i = 0; text[i] != '\0'; i++) {
if (text[i] == ' ') {
then add a certain amount of spaces to it