質問編集履歴
1
解決verを更新しました。
title
CHANGED
File without changes
|
body
CHANGED
@@ -160,6 +160,131 @@
|
|
160
160
|
}
|
161
161
|
|
162
162
|
|
163
|
+
|
164
|
+
#include <stdio.h>
|
165
|
+
#include <stdlib.h>
|
166
|
+
#include <ctype.h>
|
167
|
+
|
168
|
+
typedef long ELEMENT;
|
169
|
+
|
170
|
+
#define STACK_SIZE 100
|
171
|
+
|
172
|
+
ELEMENT stack[STACK_SIZE];
|
173
|
+
int n;
|
174
|
+
|
175
|
+
/*push関数**/
|
176
|
+
void push(ELEMENT x)
|
177
|
+
{
|
178
|
+
if (n>=STACK_SIZE){
|
179
|
+
printf("stack overflow");
|
180
|
+
exit(1);
|
181
|
+
}
|
182
|
+
stack[n++]=x;
|
183
|
+
}
|
184
|
+
|
185
|
+
/*pop関数*/
|
186
|
+
ELEMENT pop()
|
187
|
+
{
|
188
|
+
if (n<=0){
|
189
|
+
printf("stack underflow");
|
190
|
+
exit(1);
|
191
|
+
}
|
192
|
+
return stack[--n];
|
193
|
+
}
|
194
|
+
|
195
|
+
int is_digit(char *formula)
|
196
|
+
{
|
197
|
+
if (*formula=='+' || *formula=='-'){
|
198
|
+
formula++;
|
199
|
+
if (*formula>='0' && *formula<='9'){
|
200
|
+
return 1;
|
201
|
+
}
|
202
|
+
return 0;
|
203
|
+
}
|
204
|
+
if (*formula>='0' && *formula<='9'){
|
205
|
+
return 1;
|
206
|
+
}
|
207
|
+
return 0;
|
208
|
+
}
|
209
|
+
|
210
|
+
|
211
|
+
解決ver↓
|
212
|
+
|
213
|
+
int main(void)
|
214
|
+
{
|
215
|
+
n=0; /*スタックの初期化*/
|
216
|
+
|
217
|
+
int s;
|
218
|
+
printf("数字データの時はスタックに積み、ピリオドの時はスタックから降ろします。(EOFで終了)\n");
|
219
|
+
printf("データ入力の方法を選んでください。\n0..キーボード/1..ファイル:");
|
220
|
+
scanf("%d",&s);putchar('\n');
|
221
|
+
long x,a,b;
|
222
|
+
FILE *fp=stdin;
|
223
|
+
|
224
|
+
if (s==1){
|
225
|
+
fp=fopen("data.txt","r");
|
226
|
+
if (fp==NULL){
|
227
|
+
printf("ファイルオープン失敗\n");
|
228
|
+
return 1;
|
229
|
+
}
|
230
|
+
}
|
231
|
+
|
232
|
+
char str[32]={0};
|
233
|
+
|
234
|
+
|
235
|
+
if (s==0)
|
236
|
+
printf("input:");
|
237
|
+
|
238
|
+
while((fscanf(fp,"%s",str)!=EOF)){
|
239
|
+
|
240
|
+
if (is_digit(str)){
|
241
|
+
x=atoi(str);
|
242
|
+
push(x);
|
243
|
+
|
244
|
+
}else{
|
245
|
+
|
246
|
+
switch (str[0]){
|
247
|
+
case '.':
|
248
|
+
pop();
|
249
|
+
break;
|
250
|
+
case '+':
|
251
|
+
b=pop();a=pop();
|
252
|
+
push(a+b);
|
253
|
+
break;
|
254
|
+
case '-':
|
255
|
+
b=pop();a=pop();
|
256
|
+
push(a-b);
|
257
|
+
break;
|
258
|
+
case '*':
|
259
|
+
b=pop();a=pop();
|
260
|
+
push(a*b);
|
261
|
+
break;
|
262
|
+
case '/':
|
263
|
+
b=pop();a=pop();
|
264
|
+
push(a/b);
|
265
|
+
break;
|
266
|
+
case ' ':
|
267
|
+
break;
|
268
|
+
case 'A': /*Aで答えを表示*/
|
269
|
+
if(n!=0)
|
270
|
+
printf("答えは%ldです。",pop());
|
271
|
+
n=0;
|
272
|
+
break;
|
273
|
+
|
274
|
+
default:
|
275
|
+
printf("不正な入力です。\n");
|
276
|
+
while ((fscanf(fp,"%s",str)!=EOF))
|
277
|
+
;
|
278
|
+
break;
|
279
|
+
}
|
280
|
+
}
|
281
|
+
}
|
282
|
+
fclose(fp);
|
283
|
+
return 0;
|
284
|
+
}
|
285
|
+
|
286
|
+
|
287
|
+
|
163
288
|
```
|
164
289
|
|
165
290
|
### 試したこと
|