提问者:小点点

在C++中如何将long转换为常量char*? [副本]


我正在制作大整数的自定义类。 我将把它们存储在最多70位数的数组中。 我想说MyBigInt k{1000000}; (我长期需要构造函数)和MyBigInt k(“4567890098765678”); 我想要MyBigInt k=“45678909876_myliteral”; 所以我需要运算符“”_myliteral(常量char*)

这就是为什么我从常客查开始*

但是我有一些问题,比如,如何将这个长转换为常量字符*并将其发送到其他构造函数。 编辑:

    struct MyBigInt {
    
private:
    static constexpr int size{70};
    std::array<int_least8_t, size> digits; 
    int rsz;
public:
    MyBigInt(const char* cci)
    {
        if (std::strlen(cci) >70) { std::cout<<"Error";}
        else
        {
            rsz=0;
            for(auto c = cci; *c; ++c, ++rsz) 
            {
                digits[rsz] = *c - '0';
            }
        }
    }
    MyBigInt(long l) : MyBigInt(l)  {} //something like this

共1个答案

匿名用户

我将假设您想要将long的十进制值转换为字符串。

因此,根据@amachi链接的问题,您可以按如下方式更改您的构造函数:

#include <sstream>
#include <cstring>

MyClass(long l) {
    std::ostringstream oss;
    oss << l;
    std::string str = oss.str();
    
    //copy the string to your char array
    yourConstCharMember = new char[str.length()];
    strcpy_s(yourConstCharMember, str.length(), str.c_str());
}

请记住,我没有测试过这一点,记得删除你析构函数中的char数组!

相关问题


MySQL Query : SELECT * FROM v9_ask_question WHERE 1=1 AND question regexp '(c++|中|如何将|long|转|换为|常量|char|副本)' ORDER BY qid DESC LIMIT 20
MySQL Error : Got error 'repetition-operator operand invalid' from regexp
MySQL Errno : 1139
Message : Got error 'repetition-operator operand invalid' from regexp
Need Help?