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 100 101 102 103 104 105 106
|
#include <stdio.h>
#include <stdarg.h>
static void clean(char *s, FILE *fp)
{
/* search ... */
char *p = strchr(s, '\n');
if (p != NULL)
{
/* ... kill */
*p = 0;
}
else
{
/* purge */
int c;
while ((c = getchar()) != '\n' && c != EOF )
{
}
}
}
static void scanf2(char const *const control, ...)
{
char line[BUFSIZ];
//recupere une chaine de caractere de l'user
fgets(line, sizeof line, stdin);
clean(line, stdin);
/* analyse */
{
va_list ap;
va_start (ap, control);
char const *p = control;
while (*p != 0)
{
if (*p == '%')
{
p++;
switch (*p)
{
case 's': /* cadena */
{
char *s = va_arg (ap, char *);
if (s != NULL)
{
/* Danger !
* On ne connait pas la taille de la destination.
* Debordement possible
*/
strcpy (s, line);
}
}
break;
case 'd': /* entier */
{
int *pd = va_arg (ap, int *);
if (pd != NULL)
{
*pd = (int) strtol(line, NULL, 10);
}
}
break;
case 'c': /* caractere */
{
char *pc = va_arg (ap, char *);
if (pc != NULL)
{
*pc = line[0];
}
}
break;
}
}
p++;
}
va_end(ap);
}
}
int main(void)
{
{
int i;
printf ("i = ?\n");
scanf2("%d", &i);
printf ("i = %d\n", i);
}
{
char c;
printf ("c = ?\n");
scanf2("%c", &c);
printf ("c = '%c'\n", c);
}
{
char s[10];
printf ("s = ? (9 car max)\n");
scanf2("%s", s);
printf ("s = '%s'\n", s);
}
return 0;
} |
Partager