C ++ cout分离

时间:2017-09-19 12:28:30

标签: c++

我想知道是否有办法设置(#)所以我的couts是对齐的,如果我改变我的措辞,他们会继续对齐。所以我想我要问的是打印出与指标分开的值,几乎就像有自己的列一样?

示例输出: (原始)

Enter the meal price for the first guest: $45.00
Enter the meal price for the second guest: $50.00
Enter the meal price for the third guest: $100.00

Tax:                             $13.16
Tip:                             $41.63
Total Bill:                      $249.79
Tip Per Person:                  $13.88
Total Per Person:                $83.26
The 3rd guest saved:             $16.74

(更改文字)

Enter the meal price for the first guest: $45.00
Enter the meal price for the second guest: $50.00
Enter the meal price for the third guest: $100.00

Tax:                             $13.16
Gratuity:                        $41.63
Total Bill:                      $249.79
Tip Per Person:                  $13.88
Total Per Person:                $83.26
The 3rd guest saved:             $16.74

(我的代码)

#include <iomanip> //std:setprecision
#include <iostream>

using namespace std;

int main() {

    double ppl1, ppl2, ppl3, meal_total, tax, tip, total, total_bill, per_tip, per_total;

    // Get the cost of the meal
    cout << "Enter the meal price for the first guest: $";
    cin >> ppl1;
    // Get the cost of the meal
    cout << "Enter the meal price for the second guest: $";
    cin >> ppl2;
    // Get the cost of the meal
    cout << "Enter the meal price for the third guest: $";
    cin >> ppl3;
    cout << endl;
    // Caluates the tax & tip & total
    meal_total = ppl1 + ppl2 + ppl3;
    tax = meal_total * 6.75 / 100;
    tip = (tax + meal_total) * 20 / 100;
    total_bill = (tax + meal_total) + tip;
    per_tip = tip / 3;
    per_total = total_bill / 3;

    // I do not have the extra credit in place
    cout << "\nTax:                 $" << setprecision(2) << fixed << tax;
    cout << "\nTip:                 $" << setprecision(2) << fixed << tip;
    cout << "\nTotal bill:          $" << setprecision(2) << fixed << total_bill;
    cout << "\nTip per person:      $" << setprecision(2) << fixed << per_tip;
    cout << "\nTotal per person:    $" << setprecision(2) << fixed << per_total << endl;

    // Additional Lab2A adding starts here:
    // Adding vars to calulate savings on an per User basis
    // then "If" the "Guest total" is greater then 0 we are displaying savings

    double ppl1_Tax = ppl1 * 6.75 / 100;
    ;
    double ppl1_Tip = (tax + ppl1) * 20 / 100;
    double Price_ppl1 = (ppl1 + ppl1_Tax) + ppl1_Tip;
    if ((Price_ppl1 - per_total) > 0) {
        cout << "The 1st guest saved: $" << (Price_ppl1 - per_total) << endl;
    }

    double ppl2_Tax = ppl2 * 6.75 / 100;
    ;
    double ppl2_Tip = (tax + ppl2) * 20 / 100;
    double Price_ppl2 = (ppl2 + ppl2_Tax) + ppl2_Tip;
    if ((Price_ppl2 - per_total) > 0) {
        cout << "The 2nd guest saved: $" << (Price_ppl2 - per_total) << endl;
    }

    double ppl3_Tax = ppl3 * 6.75 / 100;
    ;
    double ppl3_Tip = (tax + ppl3) * 20 / 100;
    double Price_ppl3 = (ppl3 + ppl3_Tax) + ppl3_Tip;
    if ((Price_ppl3 - per_total) > 0) {
        cout << "The 3rd guest saved: $" << (Price_ppl3 - per_total) << endl;
    }

    return 0;
}

2 个答案:

答案 0 :(得分:2)

您回答了自己的问题,只需使用setw(width),帮助函数示例:

void print_padded(const std::string& word, int width) {
    std::cout << std::left << std::setw(width) << std::setfill(' ') << word;
};

添加更多信息,如果您不知道words是否会大于width,请跟踪最大的word并设置width } word.length() + 2或类似的东西。

答案 1 :(得分:0)

你可以从昨天的答案中获取灵感:

How to write in text file by line and column using C++

同样,您可以在实际打印之前收集可打印的行。然后,您可以在打印前推断出标题列的最小所需宽度。

同时,删除代码中的重复并使用富有表现力的名称也可以改善它:

Live On Coliru

#include <iomanip> //std:std::setprecision
#include <iostream>
#include <vector>
#include <algorithm>

struct Pricing {
    double _base;
    static constexpr double tax_rate = 0.0675;
    static constexpr double tip_rate = 0.20;

    double tax() const      { return _base * tax_rate;       } 
    double tip() const      { return with_tax() * tip_rate;         } 

    double with_tax() const { return _base * (1 + tax_rate); } 
    double with_tip() const { return with_tax() * (1 + tip_rate);   } 
};

struct DinnerParty {
    struct Party {
        std::string name;
        double base_price;
    };

    using Parties = std::vector<Party>;

    DinnerParty(Parties parties) : _parties(std::move(parties)) { }

    Parties const& parties() const { return _parties;                      } 
    size_t head_count() const      { return _parties.size();               } 
    Pricing total() const          { return { base_total()              }; } 
    Pricing per_head() const       { return { base_total()/head_count() }; } 

  private:
    Parties const _parties;

    double base_total() const {
        double base = 0;
        for (auto& p : _parties) base += p.base_price;
        return base;
    }
};

template <typename ColDefs>
void printTable(ColDefs const& cols) {
    if (cols.empty())
        return;

    // find widest caption
    std::vector<int> widths;
    for (auto& col : cols)
        widths.push_back(col.caption.length());

    int width = 2 + *std::max_element(widths.begin(), widths.end());

    for (auto& col : cols)
    {
        if (col.caption.empty())
            std::cout << "\n";
        else std::cout 
            << std::left  << std::setw(width) << (col.caption+": ") << "$"
            << std::right << std::setprecision(2) << std::fixed << col.value << "\n";
    }
}

int main() {

    std::cin.exceptions(std::ios::failbit);

    auto promptPrice = [](auto name) { 
        std::cout << "Enter the meal price for " << name << ": $";
        double base_price;
        std::cin >> base_price;

        return DinnerParty::Party { name, base_price };
    };

    DinnerParty dinner({
        promptPrice("first guest"),
        promptPrice("second guest"),
        promptPrice("third guest"),
    });

    struct Row { std::string caption; double value; };

    Pricing total    = dinner.total(),
            per_head = dinner.per_head();

    std::vector<Row> rows {
        {"Tax", total.tax() },
        {"Tip", total.tip() },
        {"Total bill", total.with_tip() },
        {"Tip per person", per_head.tip() },
        {"Total per person", per_head.with_tip() },
        {"", 0}, // empty row
    };

    // Additional Lab2A adding starts here:
    // Adding vars to calulate savings on an per User basis
    // then "If" the "Guest total" is greater then 0 we are displaying savings
    for (auto& party : dinner.parties()) {
        Pricing personal {party.base_price};

        double net_gain = personal.with_tip() - per_head.with_tip();

        if (net_gain > 0)
            rows.push_back({party.name + " saved", net_gain });
    }

    printTable(rows);
}

打印

Enter the meal price for first guest: $ 17
Enter the meal price for second guest: $ 32
Enter the meal price for third guest: $ 25

Tax:                $5.00
Tip:                $15.80
Total bill:         $94.79
Tip per person:     $5.27
Total per person:   $31.60

second guest saved: $9.39
third guest saved:  $0.43