C++ – Relative Alignment of String Output

I was doing a project for my C++ class and was trying to find
an easy solution to print a string to the console and after that
string, I was to print "Record Number: " and the corresponding
number. The problem was that I needed the string to be at an 
absolute position from the left side of the screen. I read various 
blogs trying to find a simple way to do what I desired but was 
unsuccessful (doesn't mean it's not out there). The reasoning I 
was given why setw(25) wasn't working is because it was a string
object. So I developed this work-around, I am no professional
and I'm sure that someone will tell me there is a far simpler way,
but this is how I solved that problem.
#include <iomanip>
#include <iostream>
#include <string>
using namespace std;


int main()
{
	int location;
	int indent;
	bool done = false;
	// create an array of 4 names
	string names[4] = {"Chad", "Mitch", "Abbie", "Courtney"};

	do
	{
		// prompt the user for an index location
		cout << "\nEnter Record number(1-4) or 0 to quit: ";
		cin >> location;

		// input validation
		if (location == 0)
		{
			done = true;
		}
		else if (location < 0 || location > 4)
		{
			cout << "\nYou must enter a number between 1 and 4\n";
		}
		else
		{
			// Prompt for absolute positioning
			cout << "How far from the left would you like to indent: ";
			cin >> indent;

			// Store an isolated instance of the array at index "location"
			string result = names[location - 1];
			            
			// Add spaces after result until desired absolute spacing achieved
			for (int i = result.length(); i < indent; i++)
			{
			   result += " ";
			}

			result += "Record Number: ";

		   // Print formatted text
			cout << endl << result << location + 1 << endl;
		}	
	}
	while(!done);

	return 0;
}
Advertisements