Suppose you had a string that's size 77 to start with and also had a full-stop, a comma and a semi-colon in it. Then if you ran the program from line 17 of your code without checking the resultant string size at each step you'd end up with a string that was size 83. Hence some changes in this part of your code as below ...
Then suppose you break out of these nested if loops with a string size of 79, what are you going to do? There's no point in checking for whitespace because that'd add 2 to your size and take you over 80, so you need a check here that I've commented out and you can put in whatever condition you like.
Same when you break out of the while loop at the bottom of my code (below) with a string size 79, so another commented out bit for you to fill in as you wish. Finally, you have your super-long string, size 80! The program takes a bit of time to run though, so don't panic if nothing happens for a while:
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 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
|
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
#include<cctype>
using namespace std;
const int lineWidth = 80;
int main()
{
string s1;
cout << "Input string and hit return: \n";
getline(cin, s1);
if (s1.size() <= lineWidth - 2)
{
int pos;
pos = s1.find('.');
s1.insert(pos + 1, 2, ' ');
if(s1.size() <= lineWidth - 2)
{
int pos;
pos = s1.find(',');
s1.insert(pos + 1, 2, ' ');
if(s1.size() <= lineWidth - 2)
{
int pos;
pos = s1.find(';');
s1.insert(pos + 1, 2, ' ');
if(s1.size() <= lineWidth - 2)
{
int pos;
pos = s1.find('!');
s1.insert(pos + 1, 2, ' ');
if(s1.size() <= lineWidth - 2)
{
int pos;
pos = s1.find('?');
s1.insert(pos + 1, 2, ' ');
}
}
}
}
}
cout << "Your justified line is: \n"<<s1<<" with size: "<<s1.size()<<"\n";
//if(s1.size == lineWidth - 1)
//{
//do something to add a single whitespace to s1;
//}
while(s1.size() <= lineWidth - 2)
{
srand( (unsigned)time( NULL ) );
int pos = rand()%(s1.size()-1) + 1;//s1.size() - 1 since last character of existing string can't be whitespace;
if(isspace(s1.at(pos)))
{
s1.insert(pos + 1, 2, ' ');
}
}
//if(s1.size == lineWidth - 1)
//{
//do something to add a single whitespace to s1;
//}
cout<<"Super long string is: "<<s1<<"\nof size: "<<s1.size()<<"\n";
}
|
Sample Output
1 2 3 4 5 6
|
Input string and hit return:
jon.a,t?;n
Your justified line is:
jon. a, t? ; n with size: 20
Super long string is: jon. a, t? ; n
of size: 80
|
edit: this code works only if each punctuation mark is present no more than once in the string, otherwise only the first punctuation mark will be read. If there's more than one punctuation mark check some of my recent posts, I'd put out something last week I reckon about how to handle multiple delimiters through locale and facets