I'm making a sales receipt. The user enters in the name and price of the items. On the display, I want the name of the items to be aligned as well as the price of the items. Is there a way to get the setw for the objects after the name to be determined based on the name length? Since the names of the items will be of different lengths. The specific part of the codde is below.

    cout << "********************************************" << endl;
    cout << "********  S A L E S  R E C E I P T  ********" << endl;
    cout << "********************************************" << endl;
    cout << "**                                        **" << endl;
    cout << "**                                        **" << endl;
    for (i=0; i<items; i++)
    {
        cout << "**    " << name[i] << setw(3) << ": $" << setw(9) << price[i] << "            **" << endl;
    }//end for
    cout << "**                                        **" << endl;
    cout << "**                                        **" << endl;
    cout << "********************************************" << endl;

Recommended Answers

All 2 Replies

Try these for your formatting needs.

To do this just keep track of the length of the longest name and use that. For example:

int main () {
    std::vector< std::string > names;
    std::string name;
    size_t long_name = 0;
    while (std::cin >> name) {
        long_name = std::max (long_name, name.size());
        names.push_back (name);
    }
    for (std::vector< std::string >::iterator it = names.begin ();
            it != names.end(); ++it)
        std::cout << "'" << std::setw(long_name) << *it << "'" << std::endl;
    return 0;
}
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.