Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Absolute positioning in printout with cout in C++?

Tags:

How do you get "absolutely positioned" columns with cout, that leftaligns text and right-aligns numbers?

#include <iostream>
#include <iomanip>
using namespace std;

struct Human {
    char name[20];
    char name2[20];
    char name3[20];
    double pts;
};

int main() {
    int i;
    Human myHumen[3] = {
        {"Mr", "Alan", "Turing", 12.25},
        {"Ms", "Ada", "Lovelace", 15.25},
        {"Sir",  "Edgar Allan", "Poe", 45.25}
    };
    cout << "Name1" << setw(22) << "Name2" << setw(22) << "Name3" << setw(22) << "Rating" <<endl;
    cout << "-----------------------------------------------------------------------\n";
    for(i = 0; i < 3; i++) {
        cout << myHumen[i].name << setw(22) << myHumen[i].name2 << setw(22) << myHumen[i].name3 << setw(20) << myHumen[i].pts << endl;
    }//this didn't do nice printouts, with leftalign for text and rightalign with numbers
}
like image 772
Chris_45 Avatar asked Feb 08 '10 14:02

Chris_45


1 Answers

You use the "left" and "right" manipulators:

cout << std::left  << std::setw(30) << "This is left aligned"
     << std::right << std::setw(30) << "This is right aligned";

An example with text + numbers:

typedef std::vector<std::pair<std::string, int> > Vec;
std::vector<std::pair<std::string, int> > data;
data.push_back(std::make_pair("Alan Turing", 125));
data.push_back(std::make_pair("Ada Lovelace", 2115));

for(Vec::iterator it = data.begin(), e = data.end(); it != e; ++it)
{
    cout << std::left << std::setw(20) << it->first
         << std::right << std::setw(20) << it->second << "\n";
}

Which prints:

Alan Turing                          125
Ada Lovelace                        2115
like image 151
Manuel Avatar answered Oct 12 '22 23:10

Manuel