-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.c
170 lines (126 loc) · 2.22 KB
/
utils.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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <ctype.h>
#include "utils.h"
answer_t ask_question(char *question, check_func check, convert_func convert)
{
int buf_siz = 255;
char buf[buf_siz];
do
{
printf("%s\n", question);
read_string(buf, buf_siz);
}
while (!(check(buf)));
return convert(buf);
}
bool is_number(char *str)
{
int n = strlen(str);
if (n == 0)
{
return false;
}
for(int i=0; i<n; i++)
{
if (str[i]=='-'&& i==0 && n>1)
{
continue;
}
if (!isdigit(str[i]))
{
return false;
}
}
return true;
}
int clear_input_buffer()
{
int c;
do
{
c = getchar();
}
while (c != '\n' && c != EOF);
putchar('\n');
return 0;
}
/*
int ask_question_int(char *question)
{
int result = 0;
int conversions = 0;
do
{
printf("%s\n", question);
conversions = scanf("%d", &result);
clear_input_buffer();
}
while (conversions < 1);
return result;
}
*/
int ask_question_int(char *question)
{
answer_t answer = ask_question(question, is_number, (convert_func) atoi);
return answer.int_value; // svaret som ett heltal
}
int read_string(char *buf, int buf_siz)
{
int counter = -1;
int a;
do
{
counter++;
a = getchar();
buf[counter] = a;
}
while (a !='\0' && a != '\n' && counter < (buf_siz -1));
if (buf[counter] == '\n' || counter==buf_siz-1 )
{
buf[counter] = '\0';
}
if (counter == buf_siz-1)
{
clear_input_buffer();
}
return (counter);
}
bool not_empty(char *str)
{
return strlen(str) > 0;
}
char *ask_question_string(char *question)
{
return ask_question(question, not_empty, (convert_func) strdup).string_value;
}
/*
char *ask_question_string(char *question, char *buf, int buf_siz)
{
int chars=0;
do
{
printf("%s\n", question);
chars= read_string(buf, buf_siz);
}
while (chars < 1);
return strdup(buf) ;
}
*/
void print(char *str)
{
int i = 0;
while (str[i] != '\0')
{
putchar(str[i]);
i++;
}
}
void printl(char *str)
{
print(str);
print("\n");
}