Postfix'de matematiksel ifadelerle dolu bir dosyada tarama yapan ve sayıyı ekrana görüntüleyen kısmen yazılı kodum var.Süre boyunca nasıl yazılır, böylece sadece bir satır değil, tüm bir dosya okunabilir mi?
Hesaplamayı gerçekleştirirken, yalnızca bir satırda okuyacaktır ve sonra çıkacaktır. Metin dosyasındaki tüm aritmetik ifadeleri test etmek için kodu nasıl değiştiririm?
EOF
, NULL
ve '\0'
'a ulaşıldığında çıkmak için kod komutunu denedim, ancak hepsi bir satırda çıkıyor.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include <stdlib.h>
int top = -1;
float stack[500];
/* push the given data into the stack */
void push (int data) {
stack[++top] = data;
}
/* Pop the top element from the stack */
float pop() {
float data;
if (top == -1)
return -1;
data = stack[top];
stack[top] = 0;
top--;
return (data);
}
int main() {
char str[500];
FILE *p;
if((p=fopen("testfile1.txt","r"))==NULL){
printf("\n Unable to open file string.txt");
return 1;
}
while(fgets(str,500,p)!='\0'){
float data = -1, operand1, operand2, result;
for (int i = 0; i < strlen(str); i++) {
if (isdigit(str[i])) {
/*
* if the i/p char is digit, parse
* character by character to get
* complete operand
*/
data = (data == -1) ? 0 : data;
data = (data * 10) + (str[i] - 48);
continue;
}
if (data != -1) {
/* if the i/p is operand, push it into the stack */
push(data);
}
if (str[i] == '+' || str[i] == '-'
|| str[i] == '*' || str[i] == '/') {
/*
* if the i/p is an operator, pop 2 elements
* from the stack and apply the operator
*/
operand2 = pop();
operand1 = pop();
if (operand1 == -1 || operand2 == -1)
break;
switch (str[i]) {
case '+':
result = operand1 + operand2;
/* push the result into the stack */
push(result);
break;
case '-':
result = operand1 - operand2;
push(result);
break;
case '*':
result = operand1 * operand2;
push(result);
break;
case '/':
result = operand1/operand2;
push(result);
break;
}
}
data = -1;
}
if (top == 0)
printf("Output:%3.2f\n", stack[top]);
else
printf("have given wrong postfix expression\n");
return 1;
}
}
Ayrıca, okumak için gereken denklemler şunlardır:
13 1 - 2/3 155 + *
100 100 100 100 + + +
10.33 2 2 2 2 2 * * * * *
30 10 - 10 - 10 - 2 *
300 13.25 - 11 3 -/4 5 - * 3/
İlk denklemin yalnızca çalışır
İşte benim kodudur. Tüm bu denklemleri metin dosyasından okumak için döngü yapısı açısından ne yapabilirim?
'fgets()' bir 'char *' döndürdüğünü ve _is_ sözdizimsel olarak geçerli olduğunu belirtirken, '' \ 0 '' kelimesinin bir boş işaretçi sabiti olarak yazılması kesinlikle bir konudur. '0' veya' NULL' kullanın. –
Evet, bunu eklemek üzereydi. Jonathan'ın ne anlama geldiği hakkında daha fazla bilgi için http://stackoverflow.com/questions/1483232/array-of-char-should-end-at-0-or-0 adresini okuyun. Ayrıca, metin dosyasının içeriğini gösterebilir misin? – Tacocat
Yukarıdaki kodu, başka birçok hata içerdiğinden, http://codereview.stackexchange.com adresine de gönderebilirsiniz. –