6th a question about the Forum: Write Program , Input a segment from the keyboard in any convenient way Article (Each word in the article cannot exceed 20 letters), and then print it out. The width of each line must be 20 characters. If the last word of a row exceeds the range of 20 characters, move it to the next line. Add spaces between each word so that the end of each line is exactly at 20th characters.
I wrote a function that splits a string sentence into columns as required.
# Pragma warning (Disable: 4786 )
# Include < String >
# Include < Vector >
# Include < Iostream >
# Include < Sstream >
Using Namespace STD;
Const Char * Getspace (unsigned Int N)
{
Static String Buf;
If (N > Buf. Size ())
{
Buf. Assign (n,' ');
}
Return Buf. c_str () + Buf. Size () - N;
}
Void Build_line ( Const Vector < Vector < String > : Iterator > Words, Int Total_spaces, String & Line)
{
Int I = Words. Size () - 1 ;
For (Vector < Vector < String > : Iterator > : Const_iterator word = Words. Begin ();
Word ! = Words. End (); ++ Word)
{
Line + = ** Word;
If (I > 0 )
{
Const Int SC = (Total_spaces + I - 1 ) / I;
Total_spaces -= SC;
Line + = Getspace (SC );
I -- ;
}
}
}
Void Text_line_feed ( Const Char * Text, Int Line_limit, Vector < String > & Out )
{
String Buf (text );
Vector < String > Strings;
For ( Const Char * Word = Strtok (BUF. Begin (), " \ T \ n " ); Word; Word = Strtok (null, " \ T \ n " ))
Strings. push_back (Word );
Vector < Vector < String > : Iterator > Temp;
Int Len = 0 ;
For (Vector < String > : Iterator s = Strings. Begin (); s ! = Strings. End (); ++ S)
{
Const Int Slen = S -> Length ();
If (Len + Slen > = Line_limit)
{
String Line;
Const Int Space_count = Line_limit - Len + Temp. Size ();
Build_line (temp, space_count, line );
Out . Push_back (line );
Temp. Clear ();
Len = 0 ;
}
Len + = Slen + 1 ; // With at least one space
Temp. push_back (s );
}
String Line;
Build_line (temp, temp. Size () - 1 , Line ); // The last line does not count the total number of spaces
Out . Push_back (line );
}
Int Main ()
{
Vector < String > Lines;
Text_line_feed ( " A great discovery solves a great problem but there is a grain of discovery in the solution of any problem. " ,
50 , Lines );
For (Vector < String > : Iterator line = Lines. Begin (); line ! = Lines. End (); ++ Line)
Printf ( " % S \ n " , Line -> C_str ());
Return 0 ;
}