-1
// 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功能我設法打印使用while循環中的字符(CH)。我的目標是存儲字符串,所以我的後綴函數可以對它執行一些計算,因爲我試圖將中綴轉換爲後綴。如何將字符串從文件傳遞給函數?將中綴轉換爲後綴
如果你想知道,這個程序得到用戶選擇是否通過文件或手動輸入輸入一個表達式。表達式(這是一箇中綴)然後轉換爲後綴。
感謝
你爲什麼要關閉',而()'循環內的文件? – Barmar
'龜etc()'返回時到達文件的末尾'EOF',你需要測試這一特別。它返回'int',而不是'char',你需要改變'ch'的聲明。任何C教程都應該顯示如何正確執行此操作。 – Barmar
'character = ch'是什麼意思?你從來沒有宣佈任何變量。 – Barmar