Question: Create a project titled Lab7_TextJustify. Repeat the assignment assuming that the input comes from a file such as this one. The input file is guaranteed

Create a project titled Lab7_TextJustify. Repeat the assignment assuming that the input comes from a file such as this one. The input file is guaranteed to have lines under 70 characters. You do not need to move words between lines. You can save the example file in your computer (cut-and-paste is acceptable) in file unjustified.txt. In Visual Studio, you can just add this file to your project just as you do with source and header files. The output of your program should go to a different file named justified.txt. For the above example file, the output file would look like this Again, you can add this file to the project and observe its contents.

Hints: You may reuse the code from the first part of the lab assignment. Putting it in a separate function will make the code more modular. This code demonstrates how to read a file line-by-line.

The old code is:

#include #include #include #include #include #include using namespace std;

void splitText( string text, vector &words ) // Splits a string into words { string oneWord; stringstream ss( text ); while( ss >> oneWord ) words.push_back( oneWord ); }

string combineText( vector words ) // Concatenates words to a string { string text = ""; for ( int i = 0; i < words.size(); i++ ) text = text + words[i]; return text; }

bool isPunctuation( string s ) // Ends in punctuation? { string punc = ",.;:!?"; return ( punc.find( s[s.size()-1] ) != string::npos ); }

string justified( string message, int linelength ) // Justifies a supplied message { vector words; int numWords; int i, w; int tempLength = 0, remain;

splitText( message, words ); // Split into words numWords = words.size();

for ( i = 0; i < numWords - 1; i++ ) // Except last word on line ... { if ( isPunctuation( words[i] ) ) words[i] = words[i] + " "; // Add blank for any punctuation words[i] = words[i] + " "; // Add normal blank after a word }

for ( i = 0; i < words.size(); i++ ) tempLength += words[i].size(); // Find current length and number of extra blanks needed remain = linelength - tempLength;

srand( time(NULL) ); if ( remain >= 0 ) // Add blanks to remain random words for ( i = 1; i <= remain; i++ ) { w = rand() % ( numWords - 1 ); words[w] = words[w] + " "; } else cout << "Too many characters in the string" << endl;

return combineText( words ); // Recombine }

int main() { string message = "Contrary to popular belief, Lorem Ipsum is not simply random text."; cout << "Original: " + message << endl; cout << "Justified: " + justified( message, 70 ) << endl; }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!