二进制转换为八进制 栈的实现
程序代码:#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define STACK_SIZE 100
#define STACKINCREMENT 10
typedef struct
{
char *top;
char *base;
int stack_size;
} SqStack;
int Initstack(SqStack &S)
{
S.base=(char *)malloc(STACK_SIZE*sizeof(char));
if(!S.base)
exit(0);
S.top=S.base;
S.stack_size=STACK_SIZE;
return 1;
}
int Push(SqStack &S,char e)
{
if(S.top-S.base>=S.stack_size)
{
S.base=(char *)realloc(S.base,(S.stack_size+STACKINCREMENT)*sizeof(char ));
if(!S.base) exit(0);
S.top=S.base+S.stack_size;
S.stack_size=S.stack_size+STACKINCREMENT;
}
*S.top++=e;
return 1;
}
int Pop(SqStack &S,char &e)
{
if(S.top==S.base)
return 0;
e=*--S.top;
return 1;
}
int StackLen(SqStack &S)
{
return (S.top-S.base);
}
int main(void)
{
char c;
int len,i,j,sum=0;
SqStack S1;
SqStack S2;
Initstack(S1);
printf("Please input a binary number and type '#' for end\n");
scanf("%c",&c);
while(c!='#')
{
if(c=='1'||c=='0')
{
Push(S1,c);
}
scanf("%c",&c);
}
Initstack(S2);
len=StackLen(S1);
for(i=0;i<len;i=i+3)//总感觉这里错了,但具体的不知道怎样改
{
for(j=0;j<3;j++)
{
Pop(S1,c);
sum=sum+(c-48)*pow(2,j);
if(S1.base==S2.top)
break;
}
Push(S2,sum+48);
sum=0;
}
printf("The Octal from is :\n");
while(S2.base!=S2.top)
{
Pop(S2,c);
printf("%c",c);
}
putchar(10);
return 0;
}悲剧的是:输入的个数是3的倍数时,就能正确显示,一旦不是,就不对了。高手指教下吧。







