-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommand_line.c
182 lines (153 loc) · 4.98 KB
/
command_line.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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define CMD_LINE_BUFSIZE 128
#define CMD_TOK_BUFSIZE 32
#define CMD_TOK_DELIM " \t\n\r\a"
int error_converting = 0;
char *GetCommandLine() {
int bufsize = CMD_LINE_BUFSIZE;
char *buffer = malloc(bufsize * sizeof(char));
int position = 0;
int c = 0; // переменная для хранения символов
if (!buffer) {
fprintf(stderr, "ОШИБКА: не удалось аллоцировать буфер для считывания строки");
exit(EXIT_FAILURE);
}
while (1) {
c = getchar();
// выход из цикла при конце ввода '\n == 10
if (c == EOF || c == 10) {
buffer[position] = '\0';
return buffer;
}
buffer[position] = (char)c;
position++;
// реаллокация буфера при переполнении
if (position >= bufsize * sizeof(char)) {
bufsize += CMD_LINE_BUFSIZE;
buffer = realloc(buffer, bufsize * sizeof(char));
if (!buffer) {
fprintf(stderr, "ОШИБКА: не удалось реаллоцировать буфер для считывания строки");
exit(EXIT_FAILURE);
}
}
}
}
char **ParseArgs(char *line) {
int bufsize = CMD_TOK_BUFSIZE;
char **tokens = malloc(bufsize * sizeof(char *));
char *token = "";
int position = 0;
if (!tokens) {
fprintf(stderr, "ОШИБКА: не удалось аллоцировать место под строковые токены");
exit(EXIT_FAILURE);
}
token = strtok(line, CMD_TOK_DELIM);
while (token != NULL) {
tokens[position] = token;
position++;
if (position >= bufsize * sizeof(char *)) {
bufsize += CMD_TOK_BUFSIZE;
tokens = realloc(tokens, bufsize);
if (!tokens) {
fprintf(stderr, "ОШИБКА: не удалось реаллоцировать память под строковые токены");
exit(EXIT_FAILURE);
}
}
token = strtok(NULL, CMD_TOK_DELIM);
}
tokens[position] = NULL;
return tokens;
}
int GetStringLength(char *str, char delim) {
int length = 0;
while (str[length] != delim) {
length++;
}
return length;
}
int StringToInteger(char *str) {
int pos = 0;
int c = str[pos];
int res = 0;
while (c != '\0') {
if (c < 48 || c > 57) {
fprintf(stderr, "ОШИБКА: невозможно перевести строку %s в число", str);
error_converting = 1;
return 0;
}
res = res * 10 + (c - 48);
pos++;
c = str[pos];
}
return res;
}
double Power(double a, int n) {
if (n == 0) {
return 1;
}
return a * Power(a, n - 1);
}
double StringToDouble(char *str, int dot_pos) {
/*
У вещественного числа есть целая и дробная часть.
Заная координаты точки можно пройтись по целой части, умножая цифры на расстояние от точки,
а по дробной пойтись, умножая на 10 в степени разности: [точка] - [координата цифры]
*/
double result = 0;
int pos = 0;
int c = 0;
while (pos != dot_pos) {
c = str[pos];
result = result * 10 + (c - 48);
pos++;
}
while (c != '\0') {
result += (c - 48) / Power(10, pos - dot_pos);
pos++;
c = str[pos];
}
return result;
}
int FindChar(char *str, char cf) {
int pos = 0;
int c = str[pos];
int rpos = -1;
while (c != '\0') {
if (c == cf) {
rpos = pos;
break;
}
pos++;
c = str[pos];
}
return rpos;
}
int Execute(char **args) {
if (!args[0]) {
return 1;
}
char *base_command = args[0];
// TODO Реализовать логику заданных операций
if (strcmp(base_command, "in") == 0) {
char *sum_str = args[1];
double sum = 0;
int dot_pos = FindChar(sum_str, '.');
if (dot_pos == -1) {
sum = (double)StringToInteger(sum_str);
printf("В аккаунт внесена сумма %.2lf руб.\n", sum);
} else {
sum = StringToDouble(sum_str, dot_pos);
printf("В аккаунт внесена сумма %.2lf руб.\n", sum);
}
} else if (strcmp(base_command, "out") == 0) {
printf("command to take cash out \n");
} else if (strcmp(base_command, "cl") == 0) {
printf("command to cancel the last operation \n");
} else {
return 1;
}
// TODO Сохранять глобальные результаты в текстовый файл
return 1;
}