Jack welch
Jack welch

Reputation: 1707

How can I concatenate an `unsigned char` to an `std::string`?

I am trying to concatenate an unsigned char to a std::string but it gives me an error saying "operator+ not defined"

#include <string>

int main()
{
   unsigned char a = 't';
   std::string s   = "uoyriri";

   s = s + a;  // error: no match for operator
}

Upvotes: 1

Views: 10311

Answers (4)

Tudor
Tudor

Reputation: 62439

You could try the append method:

s.append(1, static_cast<char>(a));

Upvotes: 3

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272467

std::string doesn't have an operator+ overload for char. You could do the following:

s += 't';

But in general, what you probably want is a std::stringstream:

std::stringstream ss;

ss << "uoyriri";
ss << a;

ss.str();  // The resulting string

Upvotes: 3

David Heffernan
David Heffernan

Reputation: 612874

Cast the unsigned char to char and use operator +=.

Upvotes: 1

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361342

std::string has overloaded += which you can use to do that:

s += a; 

This should work.

Upvotes: 0

Related Questions