Hi i have program here that accept int as value. i wanted to translate it to accept strings in array then. i have read about using struct but i couldnt get into it. i hope someone can help me getting into that without using struct i dont know where to start i want to keep this lines of code.
#include <stdio.h>
#include <ctype.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
int top = 0;
int *stack = NULL;
int size = 0;
main()
{
int opt, num;
char cont[] = { 'y' };
clrscr();
/* <start Declaring Stack Size { */
printf("Stacking Program");
printf("\n\nData Size: ");
scanf("%d", &size);
printf("\n");
/* } end> */
/* <start Allocates size of stack { */
if(size > 0)
{
stack = malloc(size * sizeof(int));
if(stack == NULL)
{
printf("ERROR: malloc() failed\n");
exit(2);
}
}
else
{
printf("ERROR: size should be positive integer\n");
exit(1);
}
/* } end> */
while((cont[0] == 'y') || (cont[0] == 'Y'))
{
clrscr();
/* <start Main Menu { */
printf("Stacking Program");
printf("\n\nData Size: %d\n\n", size);
printf("MAIN MENU\n1. Pop\n2. Push\n3. Pick\n4. View\nChoose: ");
scanf("%d", &opt);
printf("\n");
switch(opt) {
case 1:
pop();
break;
case 2:
if(top==size)
{
printf("You can't push more data");
}
else
{
printf("Enter data for Stack[%d]: ", top+1);
scanf("%d", &num);
push(num);
}
break;
case 3:
pick();
break;
case 4:
view();
break;
default:
printf("Your choice is not on the list.");
break;
}
/* } end> */
printf("\n\nDo you want continue\(Y\/N\)?");
scanf("%s", &cont[0]);
}
free(stack);
}
pop()
{
int a;
loading();
if(top <= 0)
{
printf("Stack empty.");
return 0;
}
else
{
top--;
a=stack[top];
printf("\(Stack[%d] = %d\) removed.", top+1, a);
}
}
push(int a)
{
stack[top]=a;
top++;
loading();
}
pick()
{
loading();
if(top <= 0)
{
printf("Nothing to display.");
return 0;
}
else
{
printf("\(Stack[%d] = %d\) is the last data.", top, stack[top-1]);
}
}
view()
{
int i;
loading();
if(top <= 0)
{
printf("Nothing to display.");
return 0;
}
else
{
for(i=0;i<top;i++)
{
printf("Stack[%d] = %d\n", i+1, stack[i]);
}
}
}
loading()
{
float i, x;
float load;
int loadarea[] = { 5000, 10000, 15000, 20000, 25000, 30000 };
int percentLoad;
x=0;
load=0;
percentLoad = loadarea[random(5)];
gotoxy(26,11);
printf("[");
for(i=0;i<25;i++)
{
x = i+27;
gotoxy(x, 11);
printf("=");
delay(percentLoad);
gotoxy(51,11);
printf("]");
gotoxy(53,11);
load=(i/25)*104.5;
if(load>100)
load = 100.00;
printf("%.2f\%",load);
}
delay(60000);
for(i=0;i<60;i++) {
printf("\b \b");
}
printf("\n");
}
Easiest way is to convert your stack to store char* instead of int.
char **stack;
stack = malloc( size * sizeof(char*) );
Now, your push operation will accept a char* from some buffer that is storing the string that was just input, duplicate it with strdup, and store that new pointer in the stack.
typedef enum {
STACK_MEM_ERROR = -1,
STACK_FULL = 0,
STACK_OK = 1
} StackStatus;
StackStatus push(const char *str)
{
char *newstr;
if( top >= size ) return STACK_FULL;
newstr = strdup(str);
if( newstr == NULL ) return STACK_MEM_ERROR;
stack[top++] = newstr;
return STACK_OK;
}
When you pop a string, you just get a pointer.
char *pop()
{
if( top == 0 ) return NULL;
return stack[--top];
}
You are responsible for freeing that memory when you are finished with the pointer (by calling free).
char * val;
while( NULL != (val = pop()) )
{
printf( "I popped: %s\n", val );
free(val);
}
Related
i want to make the programm loop again and again until i type the endword ****TELOS
/* 1 */ int text_input();
int main() {
int number;
text_input();
return 0;
}
int text_input(char words[M][N]){
int l=0; /*lines, also how many words the text has */
char a;
int i=0;
printf("Enter the text. (****TELOS for stoping)");
char endword[10];
strcpy(endword, "****TELOS");
char temp[N];
while(1){
while(1) {
a = getchar();
if (a =='\n'){
if(strcmp(temp, "") == 0){
continue;
}
else{
break;
}
}
else if (a == ' '){
if(strcmp(temp, "") == 0){
continue;
}
else{
break;
}
}
else {
temp[i++] = a;
}
}
if (strcmp(temp, endword) == 0){
break;
}
else{
strcpy(words[l++],temp);
memset(temp, ' ', strlen(temp));
}
}
return 0;
}
I think your code doesn't work because you don't have set each item of endword to 0
so your code should be like that
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define N 10
#define M 10
int text_input(char words[M][N]);
int main() {
char a[M][N];
text_input(a);
return 0;
}
int text_input(char words[M][N]){
int l=0; /*lines, also how many words the text has */
char a;
int i=0;
char temp[N];
char endword[10] = {0,0,0,0,0,0,0,0,0,0};
printf("Enter the text. (****TELOS for stoping)");
strcpy(endword, "****TELOS");
while(1){
while(1) {
a = getchar();
if (a =='\n'){
if(strcmp(temp, "") == 0){
continue;
}
else{
break;
}
}
else if (a == ' '){
if(strcmp(temp, "") == 0){
continue;
}
else{
break;
}
}
else {
temp[i++] = a;
}
}
if (strcmp(temp, endword) == 0){
break;
}
else{
strcpy(words[l++],temp);
memset(temp, ' ', strlen(temp));
}
}
return 0;
}
I am having trouble understanding what I should do in the AddNumber function of my program. When the AddNumber function is called in main a pointer variable previous is created, and it takes the user's input and points it at the address of the variable newNum. I created an if statement for it to do that, but I was informed it doesn't do anything.
#include "stdio.h"
#include "string.h"
#include "stdlib.h"
typedef struct A_NewNumber{
struct A_NewNumber *next;
double newNum;
} NewNumber;
NewNumber *AddNumber(NewNumber *previous, char *input){
//char input[16];
//double numEntered = 0;
NewNumber *newNum = malloc(sizeof(NewNumber));
sscanf(input, "%lf", &newNum->newNum);
//sscanf(input, "%s", newNum->enterNumber);
//numEntered = atof(input);
/*if (previous != NULL){
previous->newNum;
}*/
newNum->next = NULL;
newNum->newNum = 0;
return newNum;
}
void PrintList(NewNumber *start){
NewNumber *currentNumber = start;
int count = 0;
while(currentNumber != NULL){
count++;
printf("Numbers:%lf\n",
currentNumber->newNum);
currentNumber = currentNumber->next;
}
printf("Total Numbers Entered%d\n", count);
}
void CleanUp(NewNumber *start){
NewNumber *freeMe = start;
NewNumber *holdMe = NULL;
while(freeMe != NULL){
holdMe = freeMe->next;
free(freeMe);
freeMe = holdMe;
}
}
int main(){
//indexNum = 0;
char command[16];
char input[16];
//float userInput;
NewNumber *userEnter = NULL;
NewNumber *start = NULL;
NewNumber *newest = NULL;
while(fgets(input, sizeof input, stdin)){
printf("Please enter a number->");
printf("Enter 'quit' to stop or 'print' to print/calculate");
sscanf(input, "%s", command);
if(newest == NULL){
start = AddNumber(NULL, input);
newest = start;
}else{
newest = AddNumber(newest, input);
}if(strncmp(command, "print", 5) == 0){
PrintList(start);
}else if(strncmp(command, "quit", 4)== 0){
printf("\n\nQuitting....\n");
break;
//userInput = enterNumber;
}
}
CleanUp(start);
return 0;
}
}
It was not that bad, was just in need of a bit of clean-up.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
// ALL CHECKS OMMITTED!
typedef struct A_NewNumber {
struct A_NewNumber *next;
double newNum;
} NewNumber;
NewNumber *AddNumber(NewNumber * previous, char *input)
{
int res;
// allocate new node
NewNumber *newNum = malloc(sizeof(NewNumber));
if (newNum == NULL) {
fprintf(stderr, "Malloc failed in AddNUmber()\n");
return previous;
}
// convert input string to float
res = sscanf(input, "%lf", &newNum->newNum);
if (res != 1) {
fprintf(stderr, "Something bad happend in AddNUmber()\n");
return previous;
}
// terminate that node
newNum->next = NULL;
// if this is NOT the first node
// put new node to the end of the list
if (previous != NULL) {
previous->next = newNum;
}
// return pointer to new node at end of the list
return newNum;
}
void PrintList(NewNumber * start)
{
NewNumber *currentNumber = start;
int count = 0;
while (currentNumber != NULL) {
count++;
printf("Numbers:%lf\n", currentNumber->newNum);
currentNumber = currentNumber->next;
}
printf("Total Numbers Entered %d\n", count);
}
void CleanUp(NewNumber * start)
{
NewNumber *freeMe = start;
NewNumber *holdMe = NULL;
while (freeMe != NULL) {
holdMe = freeMe->next;
free(freeMe);
freeMe = holdMe;
}
}
int main()
{
char input[16];
NewNumber *start = NULL;
NewNumber *newest = NULL;
int res;
// infinite loop
while (1) {
// give advise
printf("Please enter a number or\n");
printf("'quit' to stop or 'print' to print/calculate\n");
// get input from user
res = scanf("%s", input);
if (res != 1) {
if (res == EOF) {
fprintf(stderr, "Got EOF, bailing out\n");
break;
} else {
fprintf(stderr, "something bad happend, bailing out\n");
break;
}
}
// check if a command was given
if (strncmp(input, "print", 5) == 0) {
PrintList(start);
continue;
} else if (strncmp(input, "quit", 4) == 0) {
printf("\n\nQuitting....\n");
break;
}
// otherwise gather numbers
if (newest == NULL) {
start = AddNumber(NULL, input);
if (start == NULL) {
fprintf(stderr, "AddNumber returned NULL\n");
break;
}
newest = start;
} else {
newest = AddNumber(newest, input);
if (newest == NULL) {
fprintf(stderr, "AddNumber returned NULL\n");
break;
}
}
}
CleanUp(start);
return 0;
}
You should really make a habit of checking all returns and if you don't: be able to give a good reason why you didn't.
Don't forget to switch on all warnings your compiler offers. Even if you don't understand them now, Google might have an answer and if not some people here do (in that order, thank you).
I'm attempting to create a program that would allow the user to create a stack data structure using the push, pop, and peek command. However, I keep running into a segmentation fault whenever I try and use the push command! I have no idea why it's not working, because I made sure to use malloc on the stack structure. The peek and pop command are working (as far as I can tell). Any help??
#include<stdlib.h>
#include<stdio.h>
#include "stack.h"
int mainMenuChoice, pushValue;
void mainMenu() {
printf("\nEnter your option: \n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Peek\n");
printf("4. Exit\n");
scanf("%d", &mainMenuChoice);
}
Stack * initializeStack() {
Stack *new_stack;
int capacity = 100;
new_stack = (Stack *)malloc(sizeof(Stack));
new_stack->items = (int *)malloc(sizeof(int)*capacity);
new_stack->size = 0;
return new_stack;
}
void push(Stack *new_stack, int item) {
new_stack->items[new_stack->size++] = item;
}
void pop(Stack *new_stack) {
if(new_stack->size == 0) {
printf("The stack is empty, you can't pop any items!\n");
} else {
new_stack->size--;
}
}
int peek(Stack *new_stack) {
if(new_stack->size == 0) {
printf("The stack is empty.\n");
} else {
return new_stack->items[new_stack->size-1];
}
}
void menuOptions(int option) {
Stack *new_stack = initializeStack();
if(option == 1) {
Stack *new_stack;
printf("Enter an element to push: ");
scanf("%d", &pushValue);
push(new_stack, pushValue);
mainMenu();
menuOptions(mainMenuChoice);
} else if(option == 2) {
pop(new_stack);
mainMenu();
menuOptions(mainMenuChoice);
} else if(option == 3) {
peek(new_stack);
mainMenu();
menuOptions(mainMenuChoice);
} else if(option == 4) {
printf("Exiting...\n");
exit(0);
} else {
printf("Invalid input, please try again!\n");
mainMenu();
menuOptions(mainMenuChoice);
}
}
void program() {
mainMenu();
menuOptions(mainMenuChoice);
}
Also, this is the how I've structured the stack:
typedef struct Stack {
int size;
int *items;
}Stack;
Thank you so much in advance, I appreciate it!
I've simplified things a bit. You were having too many recursive calls and new_stack was being redefined [but not reallocated]. You'll still have more work to do (e.g. peek returns a value, but pop does not)
Here's the code [please pardon the gratuitous style cleanup]:
#include <stdlib.h>
#include <stdio.h>
//#include "stack.h"
typedef struct Stack {
int size;
int *items;
} Stack;
int mainMenuChoice;
int pushValue;
Stack *top_stack;
void
mainMenu()
{
printf("\nEnter your option: \n");
printf("1. Push\n");
printf("2. Pop\n");
printf("3. Peek\n");
printf("4. Exit\n");
scanf("%d", &mainMenuChoice);
}
Stack *
initializeStack()
{
Stack *new_stack;
int capacity = 100;
new_stack = (Stack *) malloc(sizeof(Stack));
new_stack->items = (int *) malloc(sizeof(int) * capacity);
new_stack->size = 0;
return new_stack;
}
void
push(Stack *new_stack, int item)
{
new_stack->items[new_stack->size++] = item;
}
void
pop(Stack *new_stack)
{
if (new_stack->size == 0) {
printf("The stack is empty, you can't pop any items!\n");
}
else {
new_stack->size--;
}
}
int
peek(Stack *new_stack)
{
if (new_stack->size == 0) {
printf("The stack is empty.\n");
return -1;
}
else {
return new_stack->items[new_stack->size - 1];
}
}
void
menuOptions(Stack *new_stack,int option)
{
if (option == 1) {
printf("Enter an element to push: ");
scanf("%d", &pushValue);
push(new_stack, pushValue);
}
else if (option == 2) {
pop(new_stack);
}
else if (option == 3) {
peek(new_stack);
}
else if (option == 4) {
printf("Exiting...\n");
exit(0);
}
else {
printf("Invalid input, please try again!\n");
}
}
int
main()
{
top_stack = initializeStack();
while (1) {
mainMenu();
menuOptions(top_stack,mainMenuChoice);
}
return 0;
}
typical beginner's phonebook program, attempting to add read and write to file capabilities. It's not compiling just fine but when I execute either functions 7 or 8, my errorhandler returns "invalid argument"
EDIT* updated code for the whole thing, including several fixes:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct phonebook
{
char cFirstName[20];
char cLastName[20];
char PhoNo[20];
} pb;
//function prototypes
void AddContact (pb * );
void DeleteContact (pb * );
void ShowContacts (pb * );
void FindContact (pb * );
void RandContact (pb * );
void FindContact (pb * );
void DeleteAll (pb *);
void Read (pb *);
void Write (pb *);
char FileName[100];
FILE *pRead;
FILE *pWrite;
int counter = 0;
main ()
{
pb *phonebook;
phonebook = (pb*) malloc(sizeof(pb)*1);
int iChoice = 0;
while (iChoice <= 8)
{
printf("\n-Choose an option- \n");
printf("\n\t(1)\tAdd Contact");
printf("\n\t(2)\tDelete Contact");
printf("\n\t(3)\tShow All Contacts");
printf("\n\t(4)\tSearch for a Contact");
printf("\n\t(5)\tRandom Contact");
printf("\n\t(6)\tDelete All Contacts");
printf("\n\n\t(7)\tWrite contacts to file");
printf("\n\t(8)\tRead contacts from file");
printf("\n\n\t(9)\tExit\n\n\t");
scanf("%d", &iChoice);
if (iChoice == 1)
{
AddContact(phonebook);
}
if (iChoice == 2)
{
DeleteContact (phonebook);
}
if (iChoice == 3)
{
ShowContacts(phonebook);
}
if (iChoice == 4)
{
FindContact(phonebook);
}
if (iChoice == 5)
{
RandContact(phonebook);
}
if (iChoice == 6)
{
DeleteAll(phonebook);
}
if (iChoice == 7)
{
Write(phonebook);
}
if (iChoice == 8)
{
Read(phonebook);
}
if (iChoice == 9)
{
free(phonebook);
return 0;
}
} //end while
} //end main
//function definitions
//add contact
void AddContact (pb * phonebook)
{
counter++; //counter incremented for each entry
realloc(phonebook, sizeof(pb)); //realloc with every new contact
printf("\nFirst Name: ");
scanf("%s", phonebook[counter-1].cFirstName);
printf("Last Name: ");
scanf("%s", phonebook[counter-1].cLastName);
printf("Phone Number: ");
scanf("%s", phonebook[counter-1].PhoNo);
printf("\n\tContact added\n");
}
//delete contact
void DeleteContact (pb * phonebook)
{
int x = 0;
char scrapcFirstName[20]; //strings for deleting original strings
char scrapcLastName[20];
char nullStr[20] = {"\0"};
printf("\nFirst name: ");
scanf("%s", scrapcFirstName);
printf("Last name: ");
scanf("%s", scrapcLastName);
//compare strings
for (x = 0; x < counter; x++)
{
if (strcmp(scrapcFirstName, phonebook[x].cFirstName) == 0)
{
for (x = 0; x < counter; x++)
{
if (strcmp(scrapcLastName, phonebook[x].cLastName) == 0)
{
strcpy(phonebook[x].cFirstName, nullStr);
strcpy(phonebook[x].cLastName, nullStr);
strcpy(phonebook[x].PhoNo, nullStr);
}//end if
else
{
printf("Invalid Input");
}
}//end for
}//end if
} // end for
counter--; // Contact deleted, update counter
printf("Contact Deleted\n");
}
// show phonebook
void ShowContacts (pb * phonebook)
{
int x = 0;
printf("\nPhonebook:\n\n ");
for( x = 0; x < counter; x++)
{
printf("\n(%d)\n", x+1);
printf("Name: %s %s\n", phonebook[x].cFirstName, phonebook[x].cLastName);
printf("Number: %s\n", phonebook[x].PhoNo);
} //end for
}
//Find a specific contact
void FindContact (pb * phonebook)
{
int x = 0;
char TempFirstName[20];
char TempLastName[20];
printf("\nWho are you looking for?");
printf("\n\nFirst Name: ");
scanf("%s", TempFirstName);
printf("Last Name: ");
scanf("%s", TempLastName);
for (x = 0; x < counter; x++)
{
if (strcmp(TempFirstName, phonebook[x].cFirstName) == 0)
{
if (strcmp(TempLastName, phonebook[x].cLastName) == 0)
{
printf("\n%s %s \n%s\n", phonebook[x].cFirstName, phonebook[x].cLastName, phonebook[x].PhoNo);
}
}
}
}
//show a random contact
void RandContact (pb * phonebook)
{
int iRand = 0;
srand(time(NULL));
iRand = rand() % counter;
int x = iRand;
printf("\n%s %s\n", phonebook[x].cFirstName, phonebook[x].cLastName);
printf("%s\n", phonebook[x].PhoNo);
}
//delete all
void DeleteAll (pb * phonebook)
{
int x = 0;
char nullStr[20] = {'\0'};
for ( x = 0; x < counter; x++ )
{
strcpy(phonebook[x].cFirstName, nullStr);
strcpy(phonebook[x].cLastName, nullStr);
strcpy(phonebook[x].PhoNo, nullStr);
--counter;
}
printf("Contacts have been wiped.\n");
}
void Read(pb * phonebook)
{
FILE *pRead;
char name[256];
printf("File to read: ");
gets(name);
pRead=fopen(name,"a");
if(pRead != NULL)
{
printf("Contact List");
while(!feof(pRead)){
fread(phonebook, sizeof (struct phonebook), 1, pRead);
fclose(pRead);
if (!feof(pRead)){
fread(phonebook, sizeof (struct phonebook), 1, pRead);
fclose(pRead);
}
}
}
else{
goto ErrorHandler;
}
exit(EXIT_SUCCESS);
ErrorHandler:
perror("The following error occured");
exit(EXIT_FAILURE);
}
void Write(pb * phonebook)
{
FILE *pWrite;
char name[256];
printf("File to write:");
gets(name);
pWrite=fopen(name,"a");
if(pWrite != NULL)
{
fwrite(phonebook, sizeof (struct phonebook), 1, pRead);
fclose(pWrite);
}
else{
goto ErrorHandler;
}
exit(EXIT_SUCCESS);
ErrorHandler:
perror("The following error occured");
exit(EXIT_FAILURE);
}
It's still giving me the same error, "invalid argument"
In read function you have used pWrite instead of pRead
pWrite=fopen(name,"a");
And checking for EOF condition for pRead
while(!feof(pRead))
The file name is not being set: char name[256]; and then fopen(name,"a") that's why fopen fails.
Apparently gets() does not work after your scanf, correct your scanf on line 49: to scanf("%d\n"
Input in C. Scanf before gets. Problem
The other problems have been already pointed out (*pRead instead of *pWrite), not closing files etc.
I need to convert infix to postfix and evaluate postfix expression. When reading from a file, I should be able to evaluate multiple expressions at once. But when I run it and it encounters an expression that is not well-formed in the sense that there are more closed parentheses than open ones, it evaluates that expression 2 or 3 times.
Code:
#include <stdio.h>
#include <conio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#define MAX 1000
typedef struct stack
{
int data[MAX];
int top;
} stack;
int priority(char);
void init(stack*);
int empty(stack*);
int full(stack*);
char pop(stack*);
void push(stack*, char);
char top(stack*);
void add(char*, char, int);
void keyboard();
void read_file();
int change(char);
void pushYO(double);
double popYO();
stack s;
char x;
int i, token, topYO = -1;
double result[MAX];
char filepath[MAX];
int main()
{
char choice;
init(&s);
system("CLS");
printf("[1] Keyboard \n[2] Read from text file \n[3] Exit \n");
scanf("%c", &choice);
if(choice != '1' && choice != '2' && choice != '3')
{
main();
}
else if(choice == '1')
{
keyboard();
}
else if(choice == '2')
{
read_file();
}
else if(choice == '3')
{
printf("\nThank you for using Kei Shirabe's \ninfix to postfix converter and evaluator! :)\n");
exit(0);
}
}
void keyboard() //the keyboard input version. this works fine
{
//code here
}
void read_file()
{
int z, count, form, paren;
double one, two, three = 1;
char infx[MAX];
char pofx[MAX];
char choice;
FILE *text = fopen("text.txt", "a");
printf("Enter path of file:");
scanf("%s",&filepath);
FILE *textYO = fopen(filepath, "r");
if((textYO) == NULL)
{
printf("\nError! Unable to open %s\n\n", filepath);
}
else
{
while((fgets(infx, MAX, textYO))!= NULL)
{
form = -1, paren = 0, count = 0, z = 0;
infx[
strlen(infx)-1] = '\0';
for (i=0; i<strlen(infx); i++)
{
if((token = infx[i]) != '\n')
{
if(isalnum(token))
{
form++;
}
else
{
if(token == '(')
{
paren++;
}
else if(token == ')')
{
paren--;
}
else
{
form--;
}
}
if (paren < 0)
{
printf("%s", infx);
fprintf(text, "%s", infx);
printf("\n\nError! Not well formed :( \n-----------------\n");
fprintf(text, "\n\nError! Not well formed :( \n-----------------\n");
}
else
if(isalnum(token))
{
add(pofx, token, count);
count++;
}
else
if(token == '(')
{
push(&s, '(');
}
else
{
if(token == ')')
while((x = pop(&s)) != '(')
{
add(pofx, x, count);
count++;
}
else
if(token == '^')
{
push(&s, token);
}
else
{
while(priority(token) <= priority(top(&s)) && !empty(&s))
{
x = pop(&s);
add(pofx, x, count);
count++;
}
push(&s, token);
}
}
}
else
{
while(!empty(&s))
{
x = pop(&s);
add(pofx, x, count);
count++;
}
}
}
if(form != 0 || paren != 0)
{
printf("%s", infx);
fprintf(text, "%s", infx);
printf("\n\nError! Not well formed :( \n-----------------\n");
fprintf(text, "\n\nError! Not well formed :( \n-----------------\n");
}
else
{
form = -1, paren = 0;
printf("%s", infx);
fprintf(text, "%s", infx);
printf("\n\nPostfix: %s \n\n", pofx);
fprintf(text, "\n\nPostfix: %s\n\n", pofx);
while((token = pofx[z++]) != '\0')
{
three = 1;
if(!isdigit(token) && !isalpha(token))
{
two = popYO();
one = popYO();
switch(token)
{
case '+':
pushYO(one+two); break;
case '-':
pushYO(one-two); break;
case '*':
pushYO(one*two); break;
case '/':
pushYO(one/two); break;
case '^':
if (two > 0)
{
for(i=0;i<two;i++)
{
three = three * one;
}
pushYO(three);
three = 1; break;
}
else
{
for(i=0;i<(two-(2*two));i++)
{
three = three * one;
}
pushYO((1/three));
three = 1; break;
}
}
}
else if(isalpha(token))
{
if(isupper(token))
{
pushYO(token - '#');
}
if(islower(token))
{
pushYO(token - change(token));
}
}
else
{
pushYO(token - '0');
}
}
printf("Result: %lf\n-----------------\n", result[topYO]);
fprintf(text, "Result: %lf\n-----------------\n", result[topYO]);
}
}
}
fclose(text);
fclose(textYO);
printf("\nRun again? \n[1] Yes \n[any other key] No\n");
scanf("%c", &choice);
scanf("%c", &choice);
if(choice == '1')
{
main();
}
else
{
printf("\nThank you for using Kei Shirabe's \ninfix to postfix converter and evaluator! :)\n");
exit(0);
}
}
//other functions down here, not important
Sample text file (and yes there is an extra space at the end):
(1+2))
(1+2*3)
For this text file, the expression (1+2)) is evaluated three times, each result being "Not well formed". The last expression works as expected.
Any help please?