在中文Windows环境下,控制台窗口中也可以用特殊符号拼出漂亮的表格来。
比如:
┌─┬─┐
│ │ │
├─┼─┤
│ │ │
└─┴─┘
其实,它是由如下的符号拼接的:
左上 = ┌
上 = ┬
右上 = ┐
左 = ├
中心 = ┼
右 = ┤
左下= └
下 = ┴
右下 = ┘
垂直 = │
水平 = ─
本题目要求编写一个程序,根据用户输入的行、列数画出相应的表格来。
例如用户输入:
3 2
则程序输出:
┌─┬─┐
│ │ │
├─┼─┤
│ │ │
├─┼─┤
│ │ │
└─┴─┘
用户输入:
2 3
则程序输出:
┌─┬─┬─┐
│ │ │ │
├─┼─┼─┤
│ │ │ │
└─┴─┴─┘
完整的程序如下:
//交流信箱:605183389@qq.com
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <vector>
using namespace std;
char szTempleate[11][4] = { "┌",
"┬",
"┐",
"├",
"┼",
"┤",
"└",
"┴",
"┘",
"│",
"─" };
char* newmem(int nLen)
{
char* ptmp = (char*)malloc(nLen);
memset(ptmp, 0, nLen);
return ptmp;
}
void makerow(int ntype, int nCol, char* pStr)
{
strncat(pStr, szTempleate[ntype], strlen(szTempleate[ntype]));
strncat(pStr, szTempleate[10], strlen(szTempleate[10]));
if (nCol > 1)
{
for (int i = 1; i < nCol; i++)
{
strncat(pStr, szTempleate[ntype + 1], strlen(szTempleate[ntype + 1]));
strncat(pStr, szTempleate[10], strlen(szTempleate[10]));
}
}
strncat(pStr, szTempleate[ntype + 2], strlen(szTempleate[ntype]));
}
int main()
{
int nRow = 3, nCol = 2;
cin >> nRow >> nCol;
if (nRow > 0 && nCol > 0)
{
vector<char*> vecStr;
int nLen = 3 * nCol * 2 + 2;
char* pStr = newmem(nLen);
strncat(pStr, szTempleate[9], strlen(szTempleate[9]));
for (int j = 0; j < nCol; j++)
{
strncat(pStr, " ", strlen(" "));
strncat(pStr, szTempleate[9], strlen(szTempleate[9]));
}
char* pTmp = newmem(nLen);
makerow(0, nCol, pTmp);
vecStr.push_back(pTmp);
pTmp = newmem(nLen);
memcpy(pTmp, pStr, nLen);
vecStr.push_back(pTmp);
if (nRow > 1)
{
for (int i = 1; i < nRow; i++)
{
pTmp = newmem(nLen);
makerow(3, nCol, pTmp);
vecStr.push_back(pTmp);
pTmp = newmem(nLen);
memcpy(pTmp, pStr, nLen);
vecStr.push_back(pTmp);
}
}
pTmp = newmem(nLen);
makerow(6, nCol, pTmp);
vecStr.push_back(pTmp);
for (int i = 0; i < vecStr.size(); i++)
{
cout << vecStr[i] << endl;
free(vecStr[i]);
}
free(pStr);
}
return 0;
}