Let's say I have a file abc.txt
. That file contains huge paragraphs of text (for example, this one: https://loremipsum.io/generator/?n=5&t=p).
I'm trying to read and print the contents of abc.txt
onto the console using stringstream
and rdbuf()
. While text displayed on the console is perfect, I would like to pad the beginning of each line by n
spaces and it's end also by the same n
spaces.
For example, the line:
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
should become:
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor
Here, I have padded the beginning and the end of the line with 4 spaces.
Note that I don't want to alter the file in any way. It itself is opened in read
mode, disallowing any writes to it.
I came across a lot of answers on SO about "centering text in C++", but most of them use setw
. It's impossible for me to know that each line may contain different width (number of characters in a line) and setw
needs to be greater than the width of the output (line).
How can I do this?
Here's how I'm reading from the file and sending it to the console out stream now:
string file_slurper(std::ifstream& infile)
{
stringstream ssm;
ssm << infile.rdbuf();
return ssm.str();
}
std::ifstream read_f(files[ch_index]);
if (read_f.is_open())
{
cout << file_slurper(read_f);
}
Also, if it helps I am using Boost
libraries is in this file, so you can suggest something from Boost as well if that's better.