Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- int main(int argc, char* const argv[]){
- FILE* archivo = stdin;
- char* buffer = NULL;
- pila_t* pila = pila_crear();
- size_t n = 0;
- size_t indice = 0;
- bool se_calculo = NULL;
- while(getline(&buffer,&n,archivo) > 0){
- char** strv = split(buffer,' ');
- size_t u = contar(strv);
- strv[u-1] = substr(strv[u-1], strlen(strv[u-1])-1);
- while(strv[indice]){
- if (es_numero(strv[indice]) && strlen(strv[indice]) != 0){
- int* numero = (int*)malloc(sizeof(int*));
- *numero = atoi(strv[indice]);
- pila_apilar(pila, (void*)numero);
- }
- if (es_operacion(strv[indice])){
- se_calculo = calcular(pila, strv[indice]);
- if (!se_calculo) break;
- }
- free(strv[indice]);
- indice++;
- }
- free(strv);
- if (!se_calculo || pila_cantidad(pila) != 1){
- fprintf(stdout,"ERROR\n");
- while(!pila_esta_vacia(pila)) free(pila_desapilar(pila));
- indice = 0;
- continue;
- }
- indice = 0;
- fprintf(stdout, "%d\n",*(int*)pila_ver_tope(pila) );
- while(!pila_esta_vacia(pila)) free(pila_desapilar(pila));
- }
- free(buffer);
- pila_destruir(pila);
- return 0;
- }
- bool calcular(pila_t* pila, char* operacion){
- if (pila_esta_vacia(pila)) return false;
- int* x = NULL;
- int* y = NULL;
- size_t cantidad_elementos = pila_cantidad(pila);
- if (strcmp("sqrt",operacion) == 0) operacion = "s";
- else if (strcmp("log",operacion) == 0) operacion = "l";
- if(strcmp(operacion,"s") == 0) {
- x = (int*)pila_desapilar(pila);
- }else{
- if (strcmp(operacion,"s") != 0 && cantidad_elementos > 1){
- x = (int*)pila_desapilar(pila);
- y = (int*)pila_desapilar(pila);
- }
- else return false;
- }
- int* res = (int*)malloc(sizeof(int*));
- switch(*operacion){
- case '+':
- *res = (*x) + (*y);
- break;
- case'-':
- *res = (*x) - (*y);
- break;
- case '*':
- *res = (*x) * (*y);
- break;
- case '/':
- if ((*y) == 0) return false;
- *res = (*x) / (*y);
- break;
- case '^':
- if ((*y) < 0) return false;
- *res = potencia(*x,*y);
- break;
- case 's':
- if ((*x) < 0) return false;
- *res = raiz(*x, (*x)/2);
- break;
- case 'l':
- if ((*y) <= 1 || (*x) < 1) return false;
- *res = logaritmo((*y),(*x));
- break;
- case '?':
- if(pila_esta_vacia(pila)) return false;
- int* z = (int*)pila_desapilar(pila);
- if ( *x == 0) *res = *z;
- else *res = *y;
- free(z);
- break;
- }
- pila_apilar(pila, (void*)res);
- free(x);
- if (*operacion != 's') free(y);
- return true;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement