【发布时间】:2020-07-20 18:15:06
【问题描述】:
我正在创建一个程序来评估包含在单行文本文件中的后缀表达式。我在处理扫描文件中的空格时遇到了一些麻烦。到目前为止,我所做的是将文件中的单行扫描到缓冲区中,然后一次处理一个字符的字符串。将行读入字符串后,如何忽略空格?例如:
2 4 3 * +
这是完整的程序:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
int stack[1000];
int top = -1;
void push(int x);
int pop();
bool isOperator(char ch);
int performOperation(int op1, int op2, char op);
int main()
{
char exp[1000], buffer[15];
int i, num, op1, op2, len, j, x;
int stack[1000];
char fileName[20];
FILE *inFile;
char *e;
printf("Please enter text file:");
scanf("%s", fileName);
inFile = fopen(fileName, "r");
if (inFile == NULL) {
printf("Error\n");
return -1;
}
int N = 0; i = 0, temp;
while (!feof(inFile)) {
fgets(buffer, 15, inFile);
N++;
}
printf("Postfix expression:\n");
printf("%s", buffer);
e = buffer;
while (*e != '\0') {
if (isdigit(*e)) {
num = *e - 48;
push(num);
} else {
op1 = pop();
op2 = pop();
if (isOperator(*e)) {
int ans;
ans = performOperation(op1, op2, *e);
}
push(ans);
}
e++;
}
printf(" The value of the expression is %d\n", ans);
}
void push(int x)
{
stack[++top] = x;
}
int pop()
{
return stack[top--];
}
bool isOperator(char ch) {
if (ch == '+' || ch == '-' || ch == '*'|| ch == '/')
return true;
else
return false;
}
int performOperation(int op1, int op2, char op) {
int ans;
switch (op) {
case '+':
ans = op2 + op1;
break;
case '-':
ans = op2 - op1;
break;
case '*':
ans = op2 * op1;
break;
case '/':
ans = op2 / op1;
break;
}
return ans;
}
感谢任何帮助。
我忘了说我们只处理一位数字。
【问题讨论】:
-
您可能应该考虑使用
strsep函数。这里有一个很好的概述:c-for-dummies.com/blog/?p=1769.
标签: c file-io postfix-notation