1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99
|
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
char* name;
int(*function_ptr )(int argc, char** argv);
}COMMANDSTRUCT;
int dummy(int argc, char** argv)
{
return -1; /* commande non implementee */
}
int add(int argc, char** argv)
{
int result = 0;
int value;
int index = 1; /* argv[0] = "add" (nom de la commande) */
while(index < argc) /* tant qu'il y a des parametres */
{
if(argv[index] == NULL)
break; /* fin des parametres */
if(sscanf(argv[index], "%i", &value) == 1)
result += value;
else
return -1; /* erreur entree non numerique */
index++;
}
printf("%i\n", result);
return 0;
}
COMMANDSTRUCT commands[] =
{
{"add", add},
{"sub", dummy},
{"mul", dummy},
{"div", dummy},
{"", NULL}/* pour detecter la fin des commandes */
};
int interpreter(char* text)
{
int argc = 0;
char* argv[20];
char buffer[80];
char* parser = buffer;
int index;
int errcode;
char car;
strcpy(buffer, text);
argv[0] = parser;
while(1) /* construction argv[1..x] */
{
car = *parser++;
switch(car)
{
case ' ':
case '\0':
*(parser - 1) = '\0';
argv[++argc] = parser;
break;
default:
break;
}
if(car == '\0') /* n'oublions pas de sortir */
break;
}
index = 0;
while(1) /* recherche argv[0] dans la table de commande */
{
if(strcmp(argv[0], commands[index].name) == 0)
{
errcode = commands[index].function_ptr(argc, argv);
break;
}
if (commands[index].function_ptr == NULL)
{
errcode = -1;
break;
}
index++;
}
return errcode;
}
int main(void)
{
printf ("%i\n", interpreter("add 33 45 67"));
printf ("%i\n", interpreter("add 1000 200 30 4"));
printf ("%i\n", interpreter("add 1000 200 30 a4"));
printf ("%i\n", interpreter("sub 1000 200 30 4"));
return 0;
} |
Partager