-
Notifications
You must be signed in to change notification settings - Fork 0
/
simplescanf.c
91 lines (87 loc) · 1.52 KB
/
simplescanf.c
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
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define MAXLN 1024
#define SPACE "\t\n\f\r "
char * check(char *bptr)
{
while (*bptr != '\n') {
if (!isspace(*bptr))
return bptr;
++bptr;
}
return bptr;
}
char *fillbuff(char *buff)
{
fgets(buff, MAXLN, stdin);
return buff;
}
int simplescanf(const char *fmt, ...)
{
char buff[MAXLN], *str, *bptr, *ch;
int len = 0, count = 0, space = 0,*var;
char tmp[MAXLN];
va_list ap;
va_start(ap, fmt);
bptr = fillbuff(buff);
while (*fmt) {
len = 0;
while (*fmt && isspace(*fmt)) {
++fmt;
++space;
}
if (!*fmt)
break;
if (*fmt == 's') {
bptr = check(bptr);
if (*bptr == '\n') {
bptr = fillbuff(buff);
continue;
}
str = va_arg(ap, char *);
len = strcspn(bptr, SPACE);
strncpy(str, bptr, len);
bptr += len;
++count;
space = 0;
} else if (*fmt == 'd') {
bptr = check(bptr);
if (*bptr == '\n') {
bptr = fillbuff(buff);
continue;
}
var = va_arg(ap, int *);
len = strcspn(bptr, SPACE);
strncpy(tmp, bptr, len);
*var = atoi(tmp);
bptr += len;
++count;
space = 0;
} else if (*fmt == 'c') {
len = 1;
if (space > 0) {
bptr = check(bptr);
if (*bptr == '\n') {
bptr = fillbuff(buff);
continue;
}
}
str = va_arg(ap, char *);
strncpy(str, bptr, len);
if (*bptr == '\n') {
bptr = fillbuff(buff);
len = 0;
}
bptr += len;
++count;
space = 0;
} else
;
++fmt;
}
va_end(ap);
return count;
}