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");
}