Answer to Question #192773 in C++ for shuvo

Question #192773

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.


1
Expert's answer
2021-05-17T03:36:18-0400
#include <string>
#include <iostream>
#include <vector>
 
using namespace std;
 
void Separator(vector<string>& formatStr);
 
 
int main()
{
	string temp;
	cout << "Enter data string: ";
	getline(cin, temp);
	string strPart;
	vector<string> formatStr;
	for (int i = 0; i < temp.size(); i++)
	{
		if (i == temp.size() - 1)
		{
			strPart += temp[i];
			formatStr.push_back(strPart);
			break;
 
		}
		if (!isspace(temp[i]))
		{
			strPart += temp[i];
			continue;
		}
		formatStr.push_back(strPart);
		strPart.clear();
	}
	cout << "****************************************" << endl;
	Separator(formatStr);
	system("pause");
	return 0;
}
 
void Separator(vector<string>& formatStr)
{
	int index = 0;
	int quantity = 0;
	for (int i = 0; i < formatStr.size(); i++)
	{
		while (true)
		{
			if (i == formatStr.size())
			{
				for (int j = i - quantity; j < i; j++)
				{
					cout << formatStr[j] << " ";
				}
				break;
			}
			index += formatStr[i].size();
			if (index > 40)
			{
				index -= formatStr[i].size();
				index--;
				i--;
				quantity--;
				int addSpace = 40 - index;
				for (int j = i - quantity; j <= i; j++)
				{
					cout << formatStr[j] << " ";
					if (addSpace > 0)
					{
						cout << " ";
						addSpace--;
					}
				}
				break;
			}
			index++;
			i++;
			quantity++;
		}
		cout << endl;
		index = 0;
		quantity = 0;
	}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment