I would like to ask for your help to review my code. As the title, I would like to print one line to multiple lines with special character as `\n` (ASCII 10), space (ASCII 32). The priority is `n`, ` `, if line doesn't contain those those characters, the code will split the string with fixed length (48, 96, ...)
1. Variables is very unclear, but I can't think a new name is better. Can you help me with those?
2. Substring from original string to a new one is copy constructor, Do you have the another approve to print it without substring?
#include <iostream>
#include <string>
struct printer
{
const std::string sep = "\n " ;
const std::size_t line_sz = 48 ;
std::string curr_line ;
printer& operator<< ( char c )
{
curr_line += c ; // append the character to the current line
// if c is a separator or character or line size has been reached
if( sep.find(c) != std::string::npos || curr_line.size() == line_sz )
{
std::cout << curr_line ; // print the current line
if( curr_line.back() != '\n' ) std::cout << '\n' ; // print a new line if required
curr_line.clear() ; // start a new line
}
return *this ;
}
~printer() // at the end
{
if( !curr_line.empty() )
{
std::cout << curr_line ; // print the last line
if( curr_line.back() != '\n' ) std::cout << '\n' ; // print a new line if required
}
}
};
Re the OP's original post and method. You might find it easier to work with iterator's and use std::find() rather than string.find(). That way you specify the start of the find and also when to stop. So if you want a line no longer than say 48 then the end iterator is the minimum of string end and string begin + 48. Everything then can be done within a loop. Then you print the required part using std::string_view from required start to required end.
#include <string>
int android_log_write( int prio, constchar *tag, constchar *text ) ;
struct printer
{
const std::string sep = "\n " ;
const std::size_t line_sz = 48 ;
constint prio = 1 ;
const std::string tag = "printer" ;
std::string curr_line ;
void do_write() // print the current line to android log
{
if( !curr_line.empty() )
{
// add a new line if the line does not end with '\n'
if( curr_line.back() != '\n' ) curr_line += '\n' ;
android_log_write( prio, tag.c_str(), curr_line.c_str() ) ;
}
}
printer& operator<< ( char c )
{
curr_line += c ; // append the character to the current line
// if c is a separator character or line size has been reached
if( sep.find(c) != std::string::npos || curr_line.size() == line_sz )
{
do_write() ; // print the current line
curr_line.clear() ; // and start a new line
}
return *this ;
}
~printer() { do_write() ; } // at the end, print the last line
};