// Function push
void push(char x){
stack[++top] = x;
}
//Function pop
char pop(){
if(top == -1)
return -1;
else
return stack[top--];
}
//Arithmetic operator precedence
int priority(char x){
if(x == '(')
return 0;
if(x == '+' || x == '-')
return 1;
if(x == '*' || x == '/')
return 2;
else
return -1;
}
//Function to convert infix to postfix
char postfix(){
char *e, x = '\0';
char exps[20];
e = exps;
printf("\nEnter an expression: \n");
scanf("%s",exps);
while(*e != '\0') //While loop to arrange stack
{
if(isalnum(*e)) //isalnum convert character to ASCII code
printf("%c",*e);
else if(*e == '(')
push(*e);
else if(*e == ')')
{
while((x = pop()) != '(')
printf("%c", x);
}
else
{
while(priority(stack[top]) >= priority(*e))
printf("%c",pop());
push(*e);
}
e++;
}
while(top != -1)
{
printf("%c",pop());
}
exit(0);
return 0;
}
//Function to read file called default input
char read_file(){
char file_location[100];
int user_option=1;
FILE *fp;
character =ch;
while (user_option == 1) {
printf("Enter the location of the file:\n\n");
getchar();
gets(file_location);
fp = fopen(file_location,"r"); //read file
if(fp == NULL)
{
perror("Error while opening the file, \n\n");
exit(EXIT_FAILURE);
}
printf("The contents of the %s file are :\n\n" , file_location);
while((*ch = fgetc(fp) !=EOF))
printf("%s" ,ch);
fclose(fp);
postfix();
break;
}
return 0;
}
int manual_input() {
int choice=0;
while(choice == 0)
{
printf("\n\t\t\t\tMENU");
printf("\n\t------------------------------");
printf("\n\n\t 1. Postfix");
printf("\n\t 2. Prefix");
printf("\n\t 3. Both");
printf("\n\t 4. Exit");
printf("\n\tWould you like to convert it to: ");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("\nYOU SELECTED OPTION 1 %c",1);
break;
case 2:
printf("\nYOU SELECTED OPTION 2 %c",2);
break;
case 3:
printf("\nYOU SELECTED OPTION 3 %c",3);
break;
default:
printf("\nYOU SELECTED OPTION 4 %c",4);
exit(0);
}
postfix();
}
return 0;
}
int main(){
printf("\nHi ,how would you like to input expression? \n");
printf("1.Get from file\n");
printf("2.Input own expression\n");
scanf("%d",&option);
if (option == 1) {
read_file();
} else {
manual_input();
}
}
Хорошо, поэтому я знаю, что мои коды немного грязные, были проблемы с отступом определенных частей кода. Надеюсь, вы все еще можете понять. Итак, мой вопрос: как получить символы из файла default.txt и передать его моей функции postfix? В моей функции read_file мне удается распечатать символы (ch), используя цикл while. Моя цель здесь - сохранить строку, чтобы моя функция postfix могла выполнять некоторые вычисления на ней, так как я пытаюсь преобразовать infix в postfix.Как передать строку из файла функции? Преобразование инфикса в постфикс
Если вам интересно, эта программа позволяет пользователю выбирать, вводить ли выражение через файл или ручной ввод. Выражение (которое представляет собой инфикс) затем преобразуется в постфикс.
Благодаря
Почему вы закрываете файл внутри 'While()' цикла? – Barmar
'fgetc()' возвращает 'EOF', когда он достигает конца файла, вам нужно проверить это специально. И он возвращает 'int', а не' char', вам нужно изменить объявление 'ch'. Любой учебник C должен показать, как это сделать правильно. – Barmar
Что означает символ 'character = ch''? Вы никогда не объявляли ни одну переменную. – Barmar