Adding spaces and new lines in printing the conten

2019-07-03 05:29发布

问题:

A have a small question. How can I add the spaces and new line signs, so that the effect looks like that?

ACCT
 CCTG
  CTGA

etc.

vector<string>::reverse_iterator it;
   for( it=vec.rbegin(); it!=vec.rend(); ++it )
   {

      cout<<*it;
      cout<<endl;
      cout<<" ";

   }

I've tried this way, but the shift is only after first element, like that:

ACCT
 CCTG
CTGA

Thanks a lot for help!

回答1:

Use this one:

std::string space = "";

for(auto it = vec.rbegin(); it != vec.rend(); ++it ) {
    std::cout << space << *it << std::endl;
    space += " ";
}

This one doesn't output the final spaces on a new line.



回答2:

vector<string>::reverse_iterator it;
   string space="";
   for( it=vec.rbegin(); it!=vec.rend(); ++it )
   {

      cout<<*it;
      cout<<endl;
      space += " ";
      cout<<space;

   }


回答3:

size_t spaces = 0;
for (auto it = vec.rbegin(); it != vec.rend(); ++it)
    cout << string(spaces++, ' ') << *it << '\n';