Aligning text in the form of vertical list/or a text in C++

250 views Asked by At

I want the following output to get aligned properly in the form of a table: enter image description here

My attempt: I created a class with member function(a function to display the products available in a store) and member variables. Then in the main function I initialized all the member variables and passed control to the user defined function to provide the output. I have provided some code snippets to support my idea.

class product
{
    public:
        //Characteristics of products
        string batchid;
        string dateofmanu; //dd-mm-yy format
        string name;
        float rate;
        int quantity;
        //User-defined functions
        void add_products();
        void mod_products();
        void del_products();
        void display_productdetails();    
};

Initializing in the main function:

int main()
{
    //Initially we have 5 products
    p[0].batchid = "Bc11256";
    p[0].dateofmanu = "08-01-2021";
    p[0].name = "Parle-G";
    p[0].rate = 25;
    p[0].quantity = 100;
    p[1].batchid = "Ad12506";
    p[1].dateofmanu = "16-01-2021";
    p[1].name = "Sun-Flakes";
    p[1].rate = 58;
    p[1].quantity = 25;
    p[2].batchid = "Af10325";
    p[2].dateofmanu = "25-01-2021";
    p[2].name = "Lays-Blue(PartyPack)";
    p[2].rate = 40;
    p[2].quantity = 100;
    p[3].batchid = "Yk63785";
    p[3].dateofmanu = "12-02-2021";
    p[3].name = "Denim T-shirt(M)";
    p[3].rate = 500;
    p[3].quantity = 50;
    p[4].batchid = "Bc11256";
    p[4].dateofmanu = "08-01-2021";
    p[4].name = "Parle-G";
    p[4].rate = 25;
    p[4].quantity = 100;
    p[4].batchid = "Hj16254";
    p[4].dateofmanu = "19-02-2021";
    p[4].name = "Tupperware WaterBottle(500ml)";
    p[4].rate = 125;
    p[4].quantity = 15;
}

Then passing control to the required user defined member function:

cout<<"The products available in the store are:\n";
                    cout<<setw(15)<<"\t\tProduct Name"<<setw(30)<<"BatchID"<<setw(30)<<"DateOfManufacturing"<<setw(15)<<"Rate"<<setw(10)<<endl;
                    for(i=0;i<5;i++)
                    p[i].display_productdetails();

User defined function to display content to user:

void product::display_productdetails()
{
    cout<<setw(15)<<"\t"<<this->name<<setw(30)<<this->batchid<<setw(30)<<this->dateofmanu<<setw(30) 
    <<this->rate<<endl;
}
1

There are 1 answers

0
rustyx On BEST ANSWER

By default when setw is set, << operator uses right-alignment.

By printing TAB characters the right-alignment is broken and the rest of the line gets shifted.

Try to avoid using \t in combination with setw, and set alignment to left in the beginning:

void product::display_productdetails()
{
    cout << left;
    cout << setw(15) << name;
    cout << setw(30) << batchid;
    cout << setw(30) << dateofmanu;
    cout << setw(30) << rate;
    cout << endl;
}