/********************************
*
* c++程序设计实践指导
*
* 1.4正整数转化为字符串
*
*********************************/
#include <iostream>
#include <string>
using namespace std;
class STR
{
struct LinkNodeA //单链表节点结构
{
short int data;
LinkNodeA *next;
};
LinkNodeA *headA;
struct LinkNodeB
{
char data;
LinkNodeB *next;
};
LinkNodeB *headB;
public:
STR(string x) //构造函数,用x初始化num
{
headA = new LinkNodeA;
headA->data = 0;
headA->next = NULL;
LinkNodeA *p, *q;
q = headA;
for(string::size_type i = 0; i < x.size(); i++)
{
p = new LinkNodeA;
p->data = x[i] - 48; //将string字符串中的字符逐个转换为int型,存入单链表1中
p->next = NULL;
q->next = p;
q = p;
}
}
void itoa(); //实现转换功能
void show() //在屏幕显示
{
LinkNodeA *p = headA->next;
LinkNodeB *q = headB->next;
cout << "下面是单链表1中各个节点存放的元素值,都是int型:" << endl;
while(p->next)
{
cout << p->data;
p = p->next;
}
cout << p->data;
cout << endl;
cout << "下面这个则是单链表2中各个节点存放的元素值,都是char型:" << endl;
while(q->next)
{
cout << q->data;
q = q->next;
}
cout << q->data;
cout << endl;
}
};
void STR::itoa() //转换
{
headB = new LinkNodeB;
headB->data = '0';
headB->next = NULL;
LinkNodeA *point = headA->next;
LinkNodeB *p, *q;
q = headB;
while(point)
{
p = new LinkNodeB;
p->data = point->data + 48; //将int型字符转化为char型字符,与单链表1中元素一一对应存入单链表2中
p->next = NULL;
q->next = p;
q = p;
if(point->next)
point = point->next;
else break;
}
}
int main()
{
string b; //string类型提供方便的输入功能,能够输入任意长度的字符串,也可以是超长整数
cin >> b;
STR str(b);
str.itoa();
str.show();
system("pause");
return 0;
}
转载于:https://my.oschina.net/u/862938/blog/111749