Align cout format as table's columns

前端 未结 4 1735
后悔当初
后悔当初 2020-12-03 04:48

I\'m pretty sure this is a simple question in regards to formatting but here\'s what I want to accomplish:

I want to output data onto the screen using cout

相关标签:
4条回答
  • 2020-12-03 05:10

    you can do it with

    string str = "somthing";
    printf ("%10s",str);
    printf ("%10s\n",str);
    printf ("%10s",str);
    printf ("%10s\n",str);
    
    0 讨论(0)
  • 2020-12-03 05:14

    You must find the length of the longest string in the first column. Then you need to output each string in the first column in a field with the length being that of that longest string. This necessarily means you can't write anything until you've read each and every string.

    0 讨论(0)
  • 2020-12-03 05:21

    I advise using Boost Format. Use something like this:

    cout << format("%|1$30| %2%") % var1 % var2;
    
    0 讨论(0)
  • 2020-12-03 05:29

    setw.

    #include <iostream>
    #include <iomanip>
    using namespace std;
    
    int main () {
      cout << setw(21) << left << "Test"    << 1 << endl;
      cout << setw(21) << left << "Test2"   << 2 << endl;
      cout << setw(21) << left << "Iamlongverylongblah"     << 2 << endl;
      cout << setw(21) << left << "Etc"     << 1 << endl;
      return 0;
    }
    
    0 讨论(0)
提交回复
热议问题