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:
#include <iostream>
#include <iomanip>
#include <string>
std::string right_justify ( const std::string& s, std::string::size_type field_width )
{
std::string::difference_type whitespace = field_width - s.size();
if ( whitespace > 0 )
return std::string ( whitespace, ' ' ) + s;
return s;
}
int main()
{
const int N = 10;
std::cout<< std::right << std::setfill ( ' ' ) << std::setw ( N ) << "12345" <<'\n';
std::cout<< right_justify ( "12345", N ) <<'\n';
}
Reputation Points: 6442
Solved Threads: 1393
Bad Cop
Offline 11,807 posts
since Sep 2004