在图形环境中很容易做出漂亮的表格。但在控制台环境中就比较困难了。有的时候可以用一些符号大略地模拟:(word文档中可能不整齐,拷贝到记事本中看)
+-------+------+
|abc |xyz=tt|
+-------+------+
|hellomm|t2 |
+-------+------+
本题目要求设计一个程序,把用户输入的内容用这种“准表格”的方式展现出来。具体的要求是:
用户输入的第一行是一个整数,表示接下来有多少行信息。接下来的每行由若干单元组成。单元间用逗号分开。
程序输出:用表格方式重新展现的输入内容。
例如:
用户输入:
3
cat,dog,good-luck
1,2,5
do not use,,that
则程序输出:(word文档中可能不整齐,拷贝到记事本中看)
+----------+---+---------+
|cat |dog|good-luck|
+----------+---+---------+
|1 |2 |5 |
+----------+---+---------+
|do not use| |that |
+----------+---+---------+
从中不难看出:
两个连续的逗号表示中间有一个内容为空的单元
列的数目由最大的单元数的那行决定
列的宽度由同列的最宽的单元决定
单元格中的信息左对齐
可以假设:用户输入的最大行数为30,可能的最多列数为40。
好像还有点错误唉~~以后再改~~某些例子我没得到结果,我已经凌乱了,不想改了~~
#include <iostream>
#include<string>
#include<vector>
using namespace std;
void show(int COL,vector<int> cont);
int main()
{
int ROW,COL,MaxLen;
vector<int> cont;
string str;
cout<<"input the numbers of the line:";
cin>>ROW;
if(ROW>30||ROW<1) cerr<<"ERRO!"<<endl;
vector<string> vec;
for(int i=0;i<ROW;i++){
cin>>str;
vec.push_back(str);
vec[i].push_back(',');
}
//首先第一行 ,为了首先创建容器
int i=0;
for(string::iterator iter=vec[0].begin();iter<vec[0].end();iter++,i++)
if(*iter==',')
cont.push_back(i);
cout<<endl;
//计算每一列的最大宽度,结果存到cont型的vector容器中
for(int k=1;k<ROW;k++){
COL=0;//用来计算列数
i=0;//用来计算最大列宽度位置
for(string::iterator iter=vec[k].begin();iter<vec[k].end();iter++,i++){
if(*iter!=',') ; //do nothing
else {
if(i>cont[COL])
cont[COL]=i;
COL++;
} //cont宽度最大的那个
}
} //最后出来时n是 有几个字符串,而i是有几个字符
//输出第一行
show(COL,cont);
cout<<endl;
for(int i=0;i<ROW;i++){
cout<<"|";
int t=0;
int w=0;
for(string::iterator iter=vec[i].begin();iter<vec[i].end();iter++,t++){
if(*iter!=',')
cout<<*iter;
else {
if(w==0)
for(int m=0;m<cont[0]-t;m++) {
cout<<" ";
}
else {
for(int m=0;m<cont[w]-cont[w-1]-t;m++)
cout<<" ";
}
t=0;
w++;
cout<<"|";
}
}
w=0;
cout<<endl;
show(COL,cont);
cout<<endl;
}
}
void show(int COL,vector<int> cont){
cout<<"+";
int m=0;
for(int j=0;j<COL;j++){
for(;m<cont[j];m++){
cout<<"-";
}
m++;
cout<<"+";
}
}