建立一个类StringInteger,把一个字符串中的数字字符转换为正整数。

11.建立一个类StringInteger,把一个字符串中的数字字符转换为正整数。
具体要求如下:
(1)私有数据成员
char*s:用动态空间存放字符串。
(2)公有成员函数
String Integer(char*str):用参数str初始化数据成员s。
operator int():转换函数,数据成员s转换整数并返回该数。 void show():输出数据成员s。
~String Integer():释放动态空间。
(3)在主函数中对定义的类进行测试。定义字符数组,把由键盘输入的字符串“ab12 3c00d45ef存
入数组,并用该数组初始化类StringInteger的对象test,调用show函数输出test的数据成员s,
然后把对象test赋值给整型变量n并输出,转换结果如下所示(下划线部分是从键盘输入的内容)
请输入字符串ab12 3c00d45ef:ab12 3c00d45ef字符串为:ab12 3c00d45ef
转换得到的整数为:1230045 


#include<iostream>
using namespace std;
class StringInteger
{
private:
	char* s;
public:
	StringInteger(char* str)
	{
		s = new char[strlen(str) + 1];
		strcpy_s(s, (strlen(str) + 1), str);
	}
	void show()
	{
		cout << "数字为:" <<*this<< endl;
	}
	operator int()
	{
		int num=0;
		//for (int i = 0; i < strlen(s) + 1; i++)
		//{
		//	if (s[i] >= '0' && s[i] <= '9')
		//	{
		//		num = num * 10 + s[i] - '0';
		//	}
		//}
		for (char* p = s; *p; p++)
		{
			if (*p >= '0' && *p <= '9')
			{
				num = num * 10 + *p- '0';
			}
		}
		return num;
	}
	~StringInteger()
	{
		delete[]s;
	}
};
int main()
{
	char str[50];
	cout << "请输入字符串“ab12 3c00d45ef”:" << endl;
	cin.getline(str, 50);
	StringInteger stri(str);
	stri.operator int();
	stri.show();
	system("pause");
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值