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.
#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;
}
}
Comments
Leave a comment