解答论坛上问题时碰到的问题,请高手看下
问题是要输入1个字符串 ,比如dsa\dw\fd,以fd\dw\dsa输出,我的思路是用栈保存最后1个是‘\’的字符串(加上可能出现的最后一个'\'后的字符串)
现在的问题是中间用来临时保存的字符串变量好象有问题
代码如下
/*
输入字符串 如ddas\daw\db
输出 db\daw\ddas
*/
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX 20
typedef struct Stack{
char * stack[MAX];
int top;
}Stack;
void init(Stack &);
void push(Stack &,char *);
void pop(Stack &);
char* gettop(Stack &);
int empty(Stack &);
void main(){
char ch[20];
//用栈存放'\'分割的字符串
Stack s;
char tm[20];
init(s);
//tmp:每个压入栈的字符串的长度
int tmp=1,len,count=0,n=0;
fgets(ch,MAX,stdin);
len=strlen(ch);
while(count<len){
if(ch[count]=='\\')
{
//判断是不是第1次入栈
if(n==0)
{
strncpy(tm,ch,tmp);
tm[tmp]='\0';
}
else
{
strncpy(tm,ch+count+1-tmp,tmp);
tm[tmp]='\0';
}
push(s,tm);
tmp=0;
n++;
}
//把最后一个'\'后的字符串压入
if(count==len-1)
{
if(ch[count]!='\\'){
strncpy(tm,ch+count-tmp+1,tmp);
tm[tmp]='\0';
push(s,tm);
}
}
count++;
tmp++;
memset(tm,'0',sizeof(char)*19);
}
while(empty(s)==0){
printf("%s",gettop(s));
pop(s);
}
}
void init(Stack &s){
s.top=-1;
}
void push(Stack &s,char *tmp){
if(s.top==MAX)
{
printf("full!");
exit(1);
}
s.stack[++(s.top)]=tmp;
}
void pop(Stack &s){
if(s.top==-1)
{
printf("empty!");
exit(1);
}
else
(s.top)--;
}
int empty(Stack &s){
if(s.top==-1)
return 1;
else
return 0;
}
char * gettop(Stack &s){
return s.stack[s.top];
}
请高手指正 谢谢