Karai
Karai

Reputation: 298

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

I try to include unsigned char variable into std::string.it throws compiletime error.

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> &'

Upvotes: 2

Views: 3771

Answers (3)

Itsik
Itsik

Reputation: 3930

Your problem is the unsigned char* SrvName. It should be char* SrvName

If you are insisting that it be unsigned char*, Then cast it.
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*.
You might be confusing the int value 207, and the string value of 207.

207 as a string is 3 chars, 58 (2), 48 (0), 55 (7)

Upvotes: 3

Igor
Igor

Reputation: 27250

Why do you use unsigned char* in the first place?

Anyway, if SrvName is null-terminated, you can do:

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

Or if you know SrvName's length, you can do:

    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. 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 += ".";
    }
}

Upvotes: 4

Mac
Mac

Reputation: 14791

You could use m_sSMTPSrvName.append(SrvName) or m_sSMTPSrvName.assign(SrvName), depending on desired behaviour. 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.

Upvotes: 0

Related Questions