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.

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';
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.