因此,我尝试在C中为后缀程序添加一个前缀,但是当我开始输入符号时,循环在第一个条目处结束。
我很确定这是某个地方的数据类型问题,但我不知道在哪里。
这是代码:
#include <stdio.h>
#include <stdlib.h>
static int N;
static char *s;
void stackinit(int max){
s = malloc(max*sizeof(int));
N = 0;
}
int stackempty(){
if(N==0)
return(1);
else
return(0);
}
void stackpush(char item){
s[N] += item;
N++;
}
int stackpop(){
N--;
return(s[N]);
}
int priority(char x){
if(x == '+' || x == '-')
return(0);
if(x == '*' || x == '/')
return(1);
}
int main(void){
int i,sum;
char input;
printf("Infix to Postfix\n");
printf("How many characters will you enter?");
scanf("%d", &sum);
stackinit(sum);
for(i = 0; i < sum; i++){
printf("Enter character: ");
scanf("%s", &input);
stackpush(input);
}
while(!stackempty()){
printf("%d ", stackpop());
}
/*for(i = 0; i < sum; i++){
}*/
}
scanf()
用于%c
读取字符,因此您的代码应为
scanf(" %c", &input);
通过在%c
说明符后面添加空格,您还会消耗可能意外添加的任何新行或空格字符,然后更正循环问题。
另一个想法是,您需要在字符串上附加一个额外的字符:空字符,即'\0'
字符。这就是为什么您需要做的原因s = malloc(max*sizeof(int) + 1);
,以便您有剩余的空间'\0'
,在这种情况下,您可以在stackPush()
函数上动态添加,如下所示:
void stackpush(char item){
s[N++] = item;
s[N] = '\0';
}
另外,在您的stackPush
职能中,您想要的s[N] = item;
不是s[N] += item;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句