|
我先后用字符串、字符数组、单向链表来实现,在输入纯数字或纯字母时没有问题,但在输入汉字时就输出了不可预料的结果:符号或其他汉字,且数量与原文本不一定相同。其中一个版本如下:
#include<iostream>
#include<string>
using namespace std;
class Data//栈中间元素
{
public:
int num;
Data*next;
Data*prior;
};
class Head:public Data//栈底(不包含数据)
{
public:
Data*top;
Data*bottom;
};
int main()
{
void warning();
void Get();
string*chioce=new string;
cout<<"请选择:A求逆序数或逆序文本 B退出\n";
cin>>*chioce;
while(true)
{
if((*chioce)[1]==NULL)
{
if((*chioce)[0]=='A')
Get();
else if((*chioce)[0]=='B')
exit(1);
else warning();
}
else warning();
cout<<"请选择:A求逆序数或逆序文本 B退出";
cin>>*chioce;
}
return 0;
}
void Get()
{
Data*Creat();
void Show(Data*);
Data*top=Creat();
Show(top);
}
Data*Creat()
{
Head*head=new Head;
cout<<"请输入您要转为逆序的数字或文本:";
string*number=new string;
cin>>*number;
int*pos=new int;
*pos=1;
head->bottom=new Data;//建立了第一点
head->top=head->bottom;//top和bottom都指向第一点
head->bottom->num=(*number)[0];//第一点记录下第一个字符
head->bottom->prior=NULL;//第一点的前驱为空
while((*number)[*pos]!=NULL)//第二个或以后字符存在时
{
head->top->next=new Data;
head->top->next->num=(*number)[*pos];
head->top->next->prior=head->top;
head->top=head->top->next;
(*pos)++;
}//top最后指向末尾的结点
head->top->next=NULL;
return head->top;
delete head,number,pos;
}
void Show(Data*top)
{
Data*p=top;
cout<<"\n转换后的数字或文本如下:";
while(top!=NULL)
{
cout<<char(top->num);
top=top->prior;
}
cout<<endl;
}
void warning()
{
cout<<"\n输入有误!请重新输入。\n";
}
恳请高手指教!(顺便问一下,我的机子装的是拼音加加,所以跟踪到DOS能输入汉字。如果没装怎样输入汉字呢?) |
|