0

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.

2
Contributors
1
Reply
2
Views
9 Years
Discussion Span
Last Post by Narue
0

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';
}
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.