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;
int main()
{
string str;
cout << "Enter a string: ";
getline(cin, str);
char tempCh;
string tempStr;
vector<string> list;
for (int i = 0; i < str.size(); i++)
{
if (i == str.size() - 1)
{
tempStr += str[i];
list.push_back(tempStr);
break;
}
if (!isspace(str[i]))
{
tempStr += str[i];
continue;
}
list.push_back(tempStr);
tempStr.clear();
}
int size = 0;
int count = 0;
for (int i = 0; i < list.size(); i++)
{
while (true)
{
if (i == list.size())
{
for (int j = i - count; j < i; j++)
{
cout << list[j] << " ";
}
break;
}
size += list[i].size();
if (size > 40)
{
size -= list[i].size();
size--;
i--;
count--;
int addSpace = 40 - size;
for (int j = i - count; j <= i; j++)
{
cout << list[j] << " ";
if (addSpace > 0)
{
cout << " ";
addSpace--;
}
}
break;
}
size++;
i++;
count++;
}
cout << endl;
size = 0;
count = 0;
}
return 0;
}
Comments
Leave a comment