查表法是项目工程中非常实用的一种编程方法,具有高效,简洁,扩展,维护性强等优点,在协议处理等工作中得到广泛的应用。
这里举一C语言/菜单处理的例子说明。
程序执行后:
菜单显示:
1 TestMode1
2 TestMode 2
3 TestMode 3
4 TestMode4
按下1键,进入序列为1的目录下,显示
1 TestMode 1.1
2 TestMode 1.2
3 TestMode 1.3
4 TestMode 1.4
5 TestMode 1.5
再选择一项,出现提示:No info ,press ESC to return.
<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />
任何菜单下,按下ESC 返回上一级菜单。
定义一张表格
|
|
|
|
|
|
结合数据表的联合体:
union TestUnion{
u16 State;
struct{
u8 st1:4;
u8 st2:4;
u8 st3:4;
u8 st4:4;
}B4;
}TestST;
定义一个输出字符串数组:
u8 OutString[][30]={
"1:TestMode 1",
"2:TestMode 2",
"3:TestMode 3",
"4:TestMode 4",
"1:TestMode 1.1",
"2:TestMode 1.2",
"3:TestMode 1.3",
"4:TestMode 1.4",
"5:TestMode 1.5",
"1:TestMode 2.1",
"2:TestMode 2.2",
"3:TestMode 2.3",
"4:TestMode 2.4",
"1:TestMode 3.1",
"2:TestMode 3.2",
"3:TestMode 3.3",
"4:TestMode 3.4",
"1:TestMode 4.1",
"2:TestMode 4.2",
"3:TestMode 4.3",
"No info, press Esc to return"
};
比如在初始状态下,ST1,ST2,ST3 都是0,这个时候按下1,则状态ST2变成1,ST状态为0010,为数据表中第2个状态,输出起始序号5,连续5个字符串,即
"1:TestMode 1.1",
"2:TestMode 1.2",
"3:TestMode 1.3",
"4:TestMode 1.4",
"5:TestMode 1.5",
每按下一个键选择菜单,查找变换后的状态输出。
附C语言测试代码如下:
#include <stdio.h>
#include <conio.h>
#define tableLen 21
typedef unsigned char u8;
typedef unsigned short u16;
union TestUnion{
u16 State;
struct{
u8 st1:4;
u8 st2:4;
u8 st3:4;
u8 st4:4;
}B4;
}TestST;
struct ChangeTable_Disp{
u16 st;
u8 StartStringIndex;
u8 StringNum;
};
struct ChangeTable_Disp TableStates[] ={
0x0000, 1 , 4,
0x0010, 5 , 5,
0x0110, 21, 1,
0x0210, 21, 1,
0x0310, 21, 1,
0x0410, 21, 1,
0x0510, 21, 1,
0x0020, 10, 4,
0x0120, 21, 1,
0x0220, 21, 1,
0x0320, 21, 1,
0x0420, 21, 1,
0x0030, 14, 4,
0x0130, 21, 1,
0x0230, 21, 1,
0x0330, 21, 1,
0x0430, 21, 1,
0x0040, 18, 3,
0x0140, 21, 1,
0x0240, 21, 1,
0x0340, 21, 1,
};
u8 OutString[][30]={
"1:TestMode 1",
"2:TestMode 2",
"3:TestMode 3",
"4:TestMode 4",
"1:TestMode 1.1",
"2:TestMode 1.2",
"3:TestMode 1.3",
"4:TestMode 1.4",
"5:TestMode 1.5",
"1:TestMode 2.1",
"2:TestMode 2.2",
"3:TestMode 2.3",
"4:TestMode 2.4",
"1:TestMode 3.1",
"2:TestMode 3.2",
"3:TestMode 3.3",
"4:TestMode 3.4",
"1:TestMode 4.1",
"2:TestMode 4.2",
"3:TestMode 4.3",
"No info, press Esc to return"
};
void ChangeState(u16 st)
{
u8 i, j;
for (i=0; i<tableLen; i++)
{
if (TableStates.st == st)
{
TestST.State = st;
for (j=0; j<TableStates.StringNum; j++)
{
printf("%s\n",OutString[TableStates.StartStringIndex - 1+j]);
}
break;
}
}
}
int main(void)
{
u8 InputChar;
u8 Index;
u16 st;
ChangeState(0);
while (1)
{
InputChar = getch();
if (InputChar == 0x1B)// esc
{
if (TestST.B4.st3 != 0)
{
st = TestST.B4.st2 * 16;
}
else
{
st = 0;
}
}
else
{
if (0 == TestST.B4.st2)
{
st = (InputChar - 48) * 16;
}
else if (0 == TestST.B4.st3)
{
st = TestST.State + (InputChar - 48) * 256;
}
else
{
continue;
}
}
ChangeState(st);
}
return 0;
}
文章评论(0条评论)
登录后参与讨论