-
Notifications
You must be signed in to change notification settings - Fork 0
/
add_from_stdin.c
122 lines (101 loc) · 2 KB
/
add_from_stdin.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#define Clear_stdin while(getchar() != '\n');
char ask_for_char(char *q, char *alt)
{
char input = 0;
// If choosen the ASCII all letters are made into the alternative (alt) string
if (!strcmp("ASCII", alt))
{
alt = malloc(sizeof(char[26]));
for(int i = 0; i < 26;)
{
alt[i] = 65+i;
//alt[26+i] = 97+i;
i++;
}
}
printf("%s [%s]\n", q, alt);
do
{
if (input)
{
printf("\nBad input '%c', try again [%s]\n", input, alt);
Clear_stdin;
}
input = getchar();
ungetc(input, stdin);
} while (strchr(alt, input) == NULL);
Clear_stdin;
return input;
}
int ask_for_int(char *q, int alt)
{
int ok = 0;
int input;
if (alt == 0)
{
printf("%s [Integers]", q);
do
{
ok = scanf("%d" , &input);
if (!ok || input < 0)
{
printf("\nBad input '%d', try again [Integers]\n", input);
Clear_stdin;
}
} while (!ok || input < 0);
}
else
{
printf("%s [1-%d]", q, alt);
do
{
ok = scanf("%d" , &input);
if (!ok || input < 1 || input > alt)
{
printf("\nBad input '%d', try again [1-%d]\n", input, alt);
Clear_stdin;
}
} while (!ok || input < 1 || input > alt);
}
Clear_stdin;
return input;
}
char* ask_for_string(char *q, int size)
{
char *input = malloc(sizeof(char[size]));
assert(input != NULL);
int ok = 0;
printf("%s [String] :", q);
do
{
ok = scanf("%s", input);
if (!ok)
{
printf("\nBad input '%s', try again [String]\n", input);
Clear_stdin;
}
} while (!ok);
//free(input);
Clear_stdin;
return input;
}
char* ask_for_sentence(char *q, int size)
{
char *input = malloc(sizeof(char[size]));
assert(input != NULL);
char c;
//int ok = 0;
printf("%s [String] :", q);
while (true)
{
c = getchar();
if (c == '\n' || c == '\0') break;
strncat(input, &c, 1);
}
return input;
}