Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Structure clash - input driven solution

23 views
Skip to first unread message

Alf P. Steinbach

unread,
Nov 9, 2015, 9:58:33 AM11/9/15
to
#include "cppx.hpp"
//using std::move;
using std::wcout;
using cppx::Boxed;
using cppx::n_items;
using cppx::String;

#include <functional>
using std::function;

#include <sstream>
using std::wistringstream;

#include <string>
using std::stoi;

void standard_output( String const& s )
{
wcout << s << "\n";
}

class Formatter
{
private:
cppx::String line_;
int max_length_;
function<void(String)> output_;

void flush()
{
output_( line_ );
line_.clear();
}

public:
void add( String const& s )
{
int const previous_length = n_items( line_ );
if( previous_length == 0 )
{}
else if( previous_length + 1 + n_items( s ) > max_length_ )
{
flush();
}
else
{
line_ += L' ';
}
line_ += s;
}

~Formatter()
{
if( n_items( line_ ) > 0 ) { flush(); }
}

explicit
Formatter(
int const max_length,
function<void(String)> output = standard_output
)
: max_length_( max_length )
, output_( move( output ) )
{}
};

enum class Status
{
all_finished, more_lines_to_do
};

auto input_one_line( Formatter& formatter )
-> Status
{
Boxed<String> line = cppx::input_line();
if( line.is_empty() ) { return Status::all_finished; }

wistringstream stream( line.item() );
String word;
while( stream >> word ) { formatter.add( word ); }
return Status::more_lines_to_do;
}

auto main( int, char** args )
-> int
{
int const w = stoi( args[1] );
Formatter formatter( w );
for( ;; )
{
Status const status = input_one_line( formatter );
if( status == Status::all_finished ) { break; }
}
}
0 new messages