Justification

Please support our C++ advertiser: Intel Parallel Studio Home
Thread Solved

Join Date: Apr 2007
Posts: 110
Reputation: kylcrow is an unknown quantity at this point 
Solved Threads: 2
kylcrow kylcrow is offline Offline
Junior Poster

Justification

 
0
  #1
May 14th, 2007
How would one right justify a string with a width of 4 and store it in a variable without being able to use cout? If that is even possible.
Last edited by kylcrow; May 14th, 2007 at 11:53 am.
Reply With Quote Quick reply to this message  
Join Date: Sep 2004
Posts: 7,614
Reputation: Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute Narue has a reputation beyond repute 
Solved Threads: 713
Team Colleague
Narue's Avatar
Narue Narue is offline Offline
Code Goddess

Re: Justification

 
0
  #2
May 14th, 2007
You need to know how long the string is, and how wide the available field space is. Then take the difference of that and if it's greater than 0, prepend that number of spaces onto the string:
  1. #include <iostream>
  2. #include <iomanip>
  3. #include <string>
  4.  
  5. std::string right_justify ( const std::string& s, std::string::size_type field_width )
  6. {
  7. std::string::difference_type whitespace = field_width - s.size();
  8.  
  9. if ( whitespace > 0 )
  10. return std::string ( whitespace, ' ' ) + s;
  11.  
  12. return s;
  13. }
  14.  
  15. int main()
  16. {
  17. const int N = 10;
  18.  
  19. std::cout<< std::right << std::setfill ( ' ' ) << std::setw ( N ) << "12345" <<'\n';
  20. std::cout<< right_justify ( "12345", N ) <<'\n';
  21. }
I'm here to prove you wrong.
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:



Similar Threads
Other Threads in the C++ Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC