简体   繁体   中英

How do I properly format this table?

I'm trying to properly format a table so that it prints out values below each column, beginning with the first character of that column. I've had success formatting three columns, but I'm unable to figure out how to format the K Count and LM Count columns so that they are printed out in a neat fashion.

What are some corrections I can make to the while loop portion of the code so that the K count and LM count columns are printed out neatly?

void printTable(const vector<int>& z, const vector<long>& x, const 
vector<long>& y,
const vector<int>& a, const vector<int>& b)
{
ostringstream ss;
ss << "\n\n\n" << setw(10) << left << "Digits" << "Input Numbers       "
    << setw(11) << right << "K Output   " << setw(6)
    << right << "K Count     " << setw(10) << right << "LM Output   " << setw(6)
    << right << "LM Count" << endl;


int i = 0, n = 0;
while (i < 5)
{
    string q = to_string(z[2*n]) + " x " + to_string(z[abs(2*n + 1)]);
    string r = to_string(x[i]);
    string s = to_string(a[i]);
    string t = to_string(y[i]);
    string u = to_string(b[i]);

    ss << setw(10) << left << (i+1) <<  q
        << setw(16) << right << r
        << setw(11) << right << s
        << setw(12) << right << t
        << setw(10) << right << u << endl;

    i++;
    n++;
}

string r = ss.str();
cout << r;
}

在此处输入图片说明

You're printing the following:
- Digits left aligned over 10 chars
- Directly followed by the input number without specifying the width
- K output right aligned over 16 chars
You should instead specify the width of the input numbers as well.
Try this:

ss << setw(10) << left  << (i+1) <<
      setw(16) << left  << q <<
      setw(10) << right << s <<
      setw(12) << right << t <<
...

The exact width of each column may not be correct. Try it out yourself.

To fix K Count output, you should reset the cursor to align left after setting the width for the previous result, then shift back right. Something like this should do what you want.

ss << setw(10) << left  << (i+1) << right
    setw(16) << left << q << right <<
    setw(11) << left << r << right <<
    setw(12) << left << s << right <<
    setw(12) << left << t << right <<
    setw(10) << left << u << right << endl;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM