You can pad the string manually with spaces like so:
#include <string>
#include <iostream>
int main()
{
std::string first("John");
std::string last("Smith");
std::string full = last + ", " + first;
int colWidth = 20;
std::cout << "12345678901234567890\n"
<< full << std::string(colWidth - full.size(), ' ')
<< "aligned after 20 characters\n";
return 0;
}
Outputs:
12345678901234567890
Smith, John aligned after 20 characters
This will work for left justifying your text, given you calculate the number of characters you print.
For right-justifying, std::setw
from <iomanip>
works well. Unlike other stream manipulators, std::setw
is not sticky, so it will only modify your next immediate output.
#include <string>
#include <iostream>
#include <iomanip>
int main()
{
std::string s("ABCDE");
int colWidth = 20;
std::cout << "12345678901234567890\n";
std::cout << std::setw(colWidth) << s << "\n";
return 0;
}
Prints
12345678901234567890
ABCDE
Putting it all together, I would left justify the first column, and right justify the second and third columns.
#include <string>
#include <iostream>
#include <iomanip>
int main()
{
std::string first("John");
std::string last("Smith");
std::string full = last + ", " + first;
int score = 100;
std::string grade("A");
std::cout << "123456789012345678901234512345\n"
<< full << std::string(20 - full.size(), ' ')
<< std::setw(5) << score
<< std::setw(5) << grade << "\n";
return 0;
}
Prints:
123456789012345678901234512345
Smith, John 100 A