有偿解答,快来教教女大学生吧

34.建立一个类 String_Integer,把一个字符串中的数字字符转换为正整数。
具体要求如下: (1)私有数据成员
 char*s:用动态空间存放字符串。 (2)公有成员函数
 String_Integer(char *str):用参数 str 初始化数据成员 s。
 operator int():转换函数。将数据成员 s 转换成正整数并返回该数。  void show():输出数据成员 s。
 ~String_Integer():释放动态空间。
(3)在主函数中对定义的类进行测试。定义字符数组,把由键盘输入的字符串“ab12 3c00d45ef”存入数组,并用该数组初始化类 String_Integer 的对象 test,调用 show 函数输出 test 的数据成员 s,然后把对象 test 赋值给整型变量 n 并输出。


#pragma once
class String_Integer
{
public:
    String_Integer();
    ~String_Integer();
    //char* s;
    operator int();

    String_Integer(char* str);
public:
    char* s;
    int slen;
    int is;
};




#include "stdafx.h"
#include "String_Integer.h"


String_Integer::String_Integer()
{
    s = new char;
}

String_Integer::~String_Integer()
{
    delete s;
}


String_Integer::String_Integer(char* str)
{
    slen = strlen(str);
    s = str;
    for (size_t i = 0; i < slen; i++)
    {
        // 只能是数字
        if (*(s + i) < 0x30 || *(s + i) > 0x39)
        {
            slen = 0;
            return;
        }
    }
}

String_Integer::operator int()
{
    // 长度不为零才能转换成正整数
    if (slen != 0)
    {
        is = 0;
        for (size_t i = 0; i < slen; i++)
        {
            is += *(s + i) - 0x30;
            if (i != slen-1)
            {
                is = is * 10;
            }
        }
        return is;
    }
    // 长度为零 返回NAN
    else
    {
        return NAN;
    }

}

界面中测试

img


这个测试似乎也看不出来啥。。。。。

所以你建立一个这样的对话框工程来打断点测吧 ≧◠◡◠≦

按钮回调函数这样写

void Ccaimi3Dlg::OnBnClickedButton1()
{
    CString str;
    GetDlgItemText(IDC_EDIT1, str);
    wchar_t* wstemp = NULL;
    wstemp = str.GetBuffer(str.GetLength());
    wcscpy_s(wstemp, str.GetLength() + 1, str);
    str.ReleaseBuffer();
    USES_CONVERSION;
    char* ctemp2 = W2A(wstemp);

    String_Integer stri2int(ctemp2);

    int iZhuan = (int)stri2int;

    SetDlgItemInt(IDC_EDIT2, iZhuan);

}