Read words

Write a program that reads words and arranges them in a paragraph so that all
other than the last one are exactly forty characters long. Add spaces between words to make
the last word extend to the margin. Distribute the spaces evenly. Use a helper function for
that purpose. A typical example would be
Four score and seven years ago our
fathers brought forth on this continent
a new nation, conceived in liberty, and
dedicated to the proposition that all
men are created equal.

I was wondering where do I start?
Off the top of my head, my approach would be:

- Read the entire paragraph into a string
- Parse the string into a vector of strings, each string containing one word
- construct a line of text by appending the words one by one. Before appending each word, check whether adding it would make the length of the line more than 40 characters.
--- if it does, then:
----- add the right number of spaces to make the line 40 characters long
----- begin a new line with the word
--- if it does not, then:
-----append it to the existing line
@faizankhan40,
You mean less than 40 characters long? Because the first line of your example is 34 chars long.
@agent max
The OP wants text to be justified 40 chars wide.

But there needs to be some effort from the OP, not

faizankhan40 wrote:
I was wondering where do I start?


Like the other posts.
Read the text one word at a time. If the word can be added to the current line, add to a vector that represents the words on the line. If the word can't be addd to the existing line then calculate the required spacing to align the line properly, display the line from the vector and clear the vector.

A simple implementation could be (not fully tested for edge conditions):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <iomanip>

constexpr size_t wpl {40};

int main()
{
	std::ifstream ifs("text.txt");

	if (!ifs)
		return (std::cout << "Cannot open file\n"), 1;

	size_t llen {};
	std::vector<std::string> lwords;

	for (std::string word; ifs >> word; ) {
		if (llen + word.size() > wpl) {
			const auto extra {wpl - llen + 1};
			const auto addit {extra / (lwords.size() - 1) + 1};
			const auto left {extra % (lwords.size() - 1)};

			for (size_t w {}; w < lwords.size(); ++w)
				std::cout << std::left << std::setw(addit + lwords[w].size() + (w < left)) << lwords[w];

			std::cout << '\n';
			lwords.clear();
			llen = 0;
		}

		llen += word.size() + (llen != wpl);
		lwords.push_back(std::move(word));
	}

	for (size_t cnt {}; const auto& w : lwords)
		std::cout << (cnt++ ? " " : "") << w;

	std::cout << '\n';
}



Four  score  and  seven  years  ago  our
fathers  brought forth on this continent
a  new nation, conceived in liberty, and
dedicated  to  the  proposition that all
men are created equal.

Last edited on
Topic archived. No new replies allowed.