简体   繁体   English

如何将未签名的char *变量插入std :: string?

[英]How to insert unsigned char* variable into std::string?

I try to include unsigned char variable into std::string.it throws compiletime error. 我尝试将未签名的char变量包含到std :: string中,这会引发编译时错误。

unsigned char* SrvName;
std::string m_sSMTPSrvName;
//srvName contains "207.45.255.45"

m_sSMTPSrvName.insert(0, SrvName);

Error 错误

   error C2664: 'std::basic_string<_Elem,_Traits,_Ax> &std::basic_string<_Elem,_Traits,_Ax>::insert(unsigned int,const std::basic_string<_Elem,_Traits,_Ax> &)' : cannot convert parameter 2 from 'const unsigned char *' to 'const std::basic_string<_Elem,_Traits,_Ax> &'

Why do you use unsigned char* in the first place? 为什么首先使用unsigned char*

Anyway, if SrvName is null-terminated, you can do: 无论如何,如果SrvName为空终止,则可以执行以下操作:

    std::string m_sSMTPSrvName=reinterpret_cast<const char*>(SrvName);

Or if you know SrvName 's length, you can do: 或者,如果您知道SrvName的长度,则可以执行以下操作:

    std::string m_sSMTPSrvName(SrvName, SrvName + Length);

EDIT: 编辑:

After reading your new comment, looks like what you actually want is to convert the numbers in the array to a string that represents an IP address. 阅读完新注释后,您真正想要的是将数组中的数字转换为代表IP地址的字符串。 You can do it this way: 你可以这样做:

#include <sstream>

for (int i = 0; i < 4; i++)
{
    std::stringstream out;
    out << (int)SrvName[i];
    m_sSMTPSrvName += out.str();

    if (i < 3)
    {
        m_sSMTPSrvName += ".";
    }
}

Your problem is the unsigned char* SrvName . 您的问题是unsigned char* SrvName It should be char* SrvName 它应该是char* SrvName

If you are insisting that it be unsigned char* , Then cast it. 如果您坚持要使用unsigned char* ,则将其unsigned char*
m_sSMTPSrvName.insert(0, (char*)SrvName);

In any case, if the value of SrvName is 207.45.255.45 you should just make it char* . 无论如何,如果SrvName值为207.45.255.45 ,则应将其设置为char*
You might be confusing the int value 207, and the string value of 207. 您可能会混淆int值207和字符串值207。

207 as a string is 3 chars, 58 (2), 48 (0), 55 (7) 207作为字符串是3个字符,58(2),48(0),55(7)

You could use m_sSMTPSrvName.append(SrvName) or m_sSMTPSrvName.assign(SrvName) , depending on desired behaviour. 您可以使用m_sSMTPSrvName.append(SrvName)m_sSMTPSrvName.assign(SrvName) ,具体取决于所需的行为。 Mind you, you should have trouble with your original approach either, so I'm not certain this will solve your problem. 提醒您,您也应该使用原始方法遇到麻烦,因此我不确定这是否可以解决您的问题。

Reference docs here and here . 在这里这里参考文档。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM