Using stringstream to indent / center output

I am learning C ++ and got a project to send a pascal triangle for output (after n-lines of calculation). Having received such an output, it is stored in the "buffer" of the string stream

1 1 1 1 2 1 1 3 3 1 

But I want it soon

  1 1 1 1 2 1 1 3 3 1 

My idea: calculate the difference between the last line and the current line length (I know the last is the longest). Then plot each line using spaces (half the difference in line length). My problem:

  • I did not understand how getLine works, and how I can extract a specific (-> last) line
  • I do not know and could not find how to edit one specific line in a string stream

Somehow I got the feeling that I'm not the best way to use stringstream.

So, this is a fairly common question: how did you solve this problem and, if possible, with strings - how?

+6
source share
2 answers

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

 #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 use setw to set the line width so that it is correctly justified. The filling in the left part of the line is set (sz - i), where sz is the total number of lines, and I is the current line. Therefore, each subsequent line has 1 less space on the left side.

Next, I need to add the original size of the string (string [i] .length ()), otherwise the string will not contain enough space for the resulting string to have the correct addition on the left side.

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

Hope this helps!

+2
source

If you have access to code that writes the original output, and if you know the number of lines N that you write, you can simply do:

 for(int i = 0; i < N; ++i) { for(int j = 0; j < N - 1 - i; ++j) sstr << " "; // write N - 1 - i spaces, no spaces for i == N. // now write your numbers the way you currently do } 
0
source

Source: https://habr.com/ru/post/914872/


All Articles