Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using stringstream to indent/center output

I'm learning c++ and got the project to send a pascal's triangle to output (after n-rows of calculation)., getting output like this, stored in a stringstream "buffer"

 1
 1 1
 1 2 1
 1 3 3 1

But what I want is rather

    1
   1 1
  1 2 1
 1 3 3 1

My idea was: calculate the difference of the last line and current line length (I know that the last one is the longest). Then pad each row using spaces (half of the line-length-difference). My Problem now is:

  • I didn't get how getLine works, neither how I might extract a specific (-> last) line
  • I don't know and could not find how to edit one specific line in a stringstream

Somehow I got the feeling that I'm not on the best way using stringstream.

So this is rather a common question: How'd you solve this problem and if possible with stringstreams - how?

like image 745
AnatraIlDuck Avatar asked May 04 '12 08:05

AnatraIlDuck


1 Answers

To know the indentation of the first line, you would need to know the number of lines in the input. Therefore you must first read in all of the input. I chose to use a vector to store the values for the convenience of the .size() member function which will give the total number of lines after reading in all input.

#include<iostream>
#include<sstream>
#include<vector>
#include<iomanip> // For setw
using namespace std;
int main()
{
  stringstream ss;
  vector<string> lines;
  string s;

  //Read all of the lines into a vector
  while(getline(cin,s)) 
    lines.push_back(s);

  // setw() - sets the width of the line being output 
  // right  - specifies that the output should be right justified 
  for(int i=0,sz=lines.size();i<sz;++i)
    ss << setw((sz - i) + lines[i].length()) << right << lines[i] << endl;

  cout << ss.str();
  return 0;
}

In this example, I am using setw to set the width of the line to be right justified. The padding on the left side of the string is given by (sz - i) where sz is the total number of lines and i is the current line. Therefore every subsequent line has 1 less space on the left hand side.

Next I need to add in the original size of the line (lines[i].length()), otherwise the line will not contain a large enough space for the resulting string to have the correct padding on the left hand side.

setw((sz - i) + lines[i].length())

Hope this helps!

like image 168
Jared Sealey Avatar answered Sep 29 '22 20:09

Jared Sealey