質問編集履歴

2

read関数の実装(ソース)の追加

2022/06/08 05:08

投稿

sakippe
sakippe

スコア21

test CHANGED
File without changes
test CHANGED
@@ -158,4 +158,100 @@
158
158
  int read(char *token[], int n)
159
159
  キーボードから数式を読み込み,数式の構成要素(トークン)に分割する.分割
160
160
  した各トークンは文字列の形で,第 1 引数に指定した配列 token に格納される.
161
-
161
+ ```C
162
+ #define MAX_INPUT_STRLEN 512 /* 1回の入力の最大長 */
163
+ #define BUFCOUNT 64
164
+
165
+ /* 標準入力から1行分の文字列を読み込み,トークンに分割する.
166
+ * 第1引数: token[]: 分割した各トークン(文字列)を格納する配列.
167
+ * 第2引数: maxTokenNum: token[]の要素数.
168
+ * 第3引数: 読み込んだトークンの個数.
169
+ * 戻り値: 読み込んだトークンの個数.
170
+ */
171
+ static int read_core(char *token[], int maxTokenNum){
172
+ static char buf[BUFCOUNT][MAX_INPUT_STRLEN * 2];
173
+ static int k=-1;
174
+ static int callcnt = 0;
175
+
176
+ int i, j;
177
+ char str[MAX_INPUT_STRLEN];
178
+ int count;
179
+
180
+
181
+ if (callcnt++ > 0){
182
+ printf("\n");
183
+ }
184
+ printf("read> ");
185
+ fflush(stdout);
186
+
187
+
188
+ if (fgets(str, MAX_INPUT_STRLEN, stdin) == NULL){
189
+ token[0] = NULL;
190
+ count = -1;
191
+ return -1;
192
+ }
193
+
194
+ i = 0;
195
+ j = 0;
196
+ k = (k+1)%BUFCOUNT;
197
+ count = 0;
198
+ while (str[i] != '\0'){
199
+
200
+ if (isWhitespace(str[i])){
201
+ i++;
202
+ continue;
203
+
204
+ } else if (str[i]=='q' || str[i]=='Q'){
205
+ count = -1;
206
+ return -1;
207
+
208
+ } else if (isNumberChar(str[i]) || str[i]=='.'){
209
+ int dotcnt = 0;
210
+
211
+ token[(count)++] = &buf[k][j];
212
+
213
+ while (isNumberChar(str[i]) || str[i] == '.'){
214
+ if (str[i] == '.'){
215
+ dotcnt++;
216
+ }
217
+ buf[k][j++] = str[i++];
218
+ }
219
+ buf[k][j++] = '\0';
220
+
221
+ if (dotcnt >= 2){
222
+ fprintf(stderr, "Error: read(): 小数点が2個以上ある数値(%s)を読み込みました\n", buf[k]);
223
+ exit(1);
224
+ }
225
+ if (buf[k][0]=='.' || buf[k][j-2]=='.' ){
226
+ fprintf(stderr, "Error: read(): 実数(%s)の形式が不正です.\n", buf[k]);
227
+ exit(1);
228
+ }
229
+
230
+ } else if (isSymbolChar(str[i])){
231
+ token[(count)++] = &buf[k][j];
232
+ buf[k][j++] = str[i++];
233
+ buf[k][j++] = '\0';
234
+
235
+ } else {
236
+ printf("Error: read(): 未知の文字('%c', %d)を検出しました\n", str[i], str[i]);
237
+ exit(1);
238
+ }
239
+
240
+ if (count > maxTokenNum-1){
241
+ fprintf(stderr, "Error: read(): 分割したトークンの数が多過ぎます.\n");
242
+ exit(1);
243
+ }
244
+ }
245
+ return count;
246
+ }
247
+
248
+ int read(char *token[], int maxTokenNum){
249
+ int r;
250
+ r = read_core(token, maxTokenNum);
251
+ while (r == 0){
252
+ r = read_core(token, maxTokenNum);
253
+ }
254
+ return r;
255
+ }
256
+ ```
257
+

1

lib1の内容

2022/06/08 04:57

投稿

sakippe
sakippe

スコア21

test CHANGED
File without changes
test CHANGED
@@ -154,3 +154,8 @@
154
154
  }
155
155
 
156
156
  ```
157
+ lib1は先生の補助プログラムを使っています。変更できません。
158
+ int read(char *token[], int n)
159
+ キーボードから数式を読み込み,数式の構成要素(トークン)に分割する.分割
160
+ した各トークンは文字列の形で,第 1 引数に指定した配列 token に格納される.
161
+