Note that there are some explanatory texts on larger screens.

plurals
  1. POAdd space to a string
    text
    copied!<p>I am trying to add a space to each space until <code>column = 0</code>. I am not sure how to do this.</p> <p>The problem is the following. If you look at a newspaper you will see that the writing is justified to fit into the columns. Write a program that reads in the width of the columns in a newspaper and then a line of text. Justify the line of text to fit into a column of that width. When your program is running, the screen should look something like this:</p> <pre class="lang-none prettyprint-override"><code>Enter the width of the column: 40 Enter a line of text: Good morning how are you? 12345678901234567890123456789012345678901234567890... Good morning how are you? </code></pre> <p>The justification is done by counting the number of gaps in the text. In the above example, there are 4 gaps. Then each gap must have spaces added to it. The number of extra spaces must be shared out as evenly as possible. In the above example, the first three gaps have 5 spaces each and the last gap has 4 spaces.</p> <p>Notes:</p> <ol> <li>If the text is longer than the column then you must report an error – don't try and break it into two lines!</li> <li>Assume that the text will have more than one word in it.</li> <li>Note the header line consisting of 123456789012345678.... this is useful to check your result. You can make this header line as long as you like – 70 spaces would be a useful length.</li> </ol> <p>Thanks</p> <pre><code>#include &lt;stdio.h&gt; int clear_input_buffer(void); int column; int c; int g; int e; int space; int length; char line[40]; int main(){ g = 0; printf("enter width of column\n"); scanf("%d", &amp;column); printf("enter line of text\n"); clear_input_buffer(); gets(line); c = 0; while(c &lt;= column){ if(g &lt;= 9) { printf("%d", g); g = g + 1; c = c + 1; } else { g = 0; printf("%d", g); g = g + 1; c = c + 1; } } printf("\n%s", line); space = 0; length = 0; for( e = 0; line[e] != '\0'; e++ ) { length = length + 1; if( line[e] == ' ' ) space = space + 1; } column = column - length; for( e = 0; line[e] != '\0'; e++ ) { if((line[e] == ' ') &amp;&amp; (column &gt; 0)) { add space to here column = column - 1; } } printf("%d\n", space); printf("%d", length); printf("%s", line); } int clear_input_buffer(void) { int ch; while (((ch = getchar()) != EOF) &amp;&amp; (ch != '\n')) /* void */; return ch; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload