一、 说明
控制台输出表格,自适应宽度
二、 源码
#include <iostream>
#include <map>
#include <string>
#include <vector>using namespace std;void printTable(vector<vector<string>> *pTableData)
{int row = pTableData->size();int column = (*pTableData)[0].size();vector<int> cloumnWidth;for (int i=0;i<column;i++){cloumnWidth.push_back(0);}for(int i=0;i<row;i++){for (int j = 0; j < column; j++){if ((*pTableData)[i][j].size() > cloumnWidth[j]){cloumnWidth[j] = (*pTableData)[i][j].size();}}}//绘制表格int tableRow = row * 2 + 1;for (int i = 0; i < tableRow; i++){if (i % 2 == 0){//+--------------+for (int j=0;j<column;j++){if (j == 0){cout << "+";}for (int k=0;k< cloumnWidth[j];k++){cout << "-";}cout << "+";}cout << endl;}else{//数据行for (int j = 0; j < column; j++){if (j == 0){cout << "|";}string content = (*pTableData)[i / 2][j];//补空int emptySize = cloumnWidth[j]- content.size();for (int k = 0; k < emptySize; k++){content.append(" ");}cout << content;cout << "|" ;}cout << endl;}}
}int main()
{vector<vector<string>> tableData;for (int i=0;i<2;i++){vector<string> vec;vec.push_back("");vec.push_back("");vec.push_back("");tableData.push_back(vec);}tableData[0][0] = "aaa";tableData[0][1] = "1234";tableData[0][2] = "qwer";tableData[1][0] = "bbbb";tableData[1][1] = "123";tableData[1][2] = "qwert";printTable(&tableData);
}