944,127 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Marked Solved
  • Views: 2055
  • C++ RSS
May 14th, 2007
0

Justification

Expand Post »
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.
Similar Threads
Reputation Points: 11
Solved Threads: 2
Junior Poster
kylcrow is offline Offline
124 posts
since Apr 2007
May 14th, 2007
0

Re: Justification

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:
C++ Syntax (Toggle Plain Text)
  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. }
Administrator
Reputation Points: 6442
Solved Threads: 1393
Bad Cop
Narue is offline Offline
11,807 posts
since Sep 2004

This thread is solved

Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C++ Forum Timeline: a department-store customer progam
Next Thread in C++ Forum Timeline: C++ Server: Multi-thread VS Single-thread





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC