优化以下代码使其拥有友好的程序界面:#include stdioh#include stdlibh#include stringh run this program using the console pauser or add your own getch systempause or input loop 定义路由表结构RTable typedef struct node
#include <stdio.h> #include <stdlib.h> #include <string.h>
typedef struct node { char dstNet[5]; int distance; char nextSkip[5]; } RTable;
RTable RT1[1000]; RTable RT2[1000]; int l1, l2;
void initRTable(RTable* RT) { printf("请为当前路由器添加路由表项(目的网络 距离 下一跳路由器):\n"); for (int i = 0; i < 1000; ++i) { scanf("%s%d%s", RT[i].dstNet, &RT[i].distance, RT[i].nextSkip); if (RT[i].distance == 0) { break; } } l1 = i; }
void addNearRouter(char* nearR) { printf("\n请输入相邻路由器名称:\n"); scanf("%s", nearR); }
void initNearRTable(RTable* RT2, char* nearR) { printf("\n请为相邻路由器%s添加路由表项(目的网络 距离 下一跳路由器):\n", nearR); for (int i = 0; i < 1000; ++i) { scanf("%s%d%s", RT2[i].dstNet, &RT2[i].distance, RT2[i].nextSkip); if (RT2[i].distance == 0) { break; } } l2 = i; }
void updateNearRTable(RTable* RT2, char* nearR) { for (int p = 0; p < l2; ++p) { RT2[p].distance = RT2[p].distance + 1; strcpy(RT2[p].nextSkip, nearR); } }
void updateRTable(RTable* RT1, RTable* RT2) { for (int p = 0; p < l2; ++p) { int finded = 0; for (int q = 0; q < l1; ++q) { if (strcmp(RT2[p].dstNet, RT1[q].dstNet) == 0) { finded = 1; if (strcmp(RT1[q].nextSkip, RT2[q].nextSkip) == 0) { RT1[q].distance = RT2[p].distance; } else { if (RT2[p].distance + 1 < RT1[q].distance) { RT1[q].distance = RT2[p].distance; strcpy(RT1[q].nextSkip, RT2[q].nextSkip); } } } } if (!finded) { strcpy(RT1[l1].dstNet, RT2[p].dstNet); RT1[l1].distance = RT2[p].distance; strcpy(RT1[l1].nextSkip, RT2[p].nextSkip); ++l1; } } }
void printRTable(RTable* RT, int len, char* title) { printf("\n----------%s的路由表---------\n", title); printf(" 目的网络 距离 下一跳路由器\n"); for (int i = 0; i < len; ++i) { printf(" %s %d %s\n", RT[i].dstNet, RT[i].distance, RT[i].nextSkip); } printf("-------------------------------------\n"); }
int main() { printf("\n-----------距离向量算法的过程模拟------------\n\n");
initRTable(RT1);
while (1) {
printf("\n-----------是否有新的路由信息(0为否,1为是)------------\n\n");
int choose;
scanf("%d", &choose);
if (choose == 1) {
char nearR[5];
addNearRouter(nearR);
initNearRTable(RT2, nearR);
printRTable(RT1, l1, "当前路由器");
printRTable(RT2, l2, "相邻路由器");
updateNearRTable(RT2, nearR);
printRTable(RT2, l2, "修改后的路由信息");
updateRTable(RT1, RT2);
printRTable(RT1, l1, "更新后的路由表");
} else {
break;
}
}
printf("\n-----------更新完毕------------\n\n");
return 0;
原文地址: https://www.cveoy.top/t/topic/fmi3 著作权归作者所有。请勿转载和采集!