Reputation:
I have two chars and I want to create a string concatenating them:
char a = '1';
char b = '2';
string s = "(" + a + "," + b + ")";
What's the easiest way to achieve that? Since the first element "(" is a string, by concatenating the elements from left to right it should work, since each char will be casted into a string and appended.
However the compiler doesn't seem to like it.
error: invalid operands of types 'const char*' and 'const char [2]' to binary 'operator+'
How can I achieve that?
Upvotes: 0
Views: 597
Reputation: 75874
"("
is not a std::string
. It is a char[2]
C string array. Make it std::string
by using the s
literal:
using namespace std::string_literals;
std::string s = "("s + a + ","s + b + ")"s;
This can still fail if you try to do something like this:
std::string s = a + b + "."s; // error
In this case you can simply start with an empty string:
std::string s = ""s + a + b + "."s;
Another option is to use std::ostringstream
to build the string:
std::ostringstream oss;
oss << "(" << a << "," << b << ")";
std::string s3 = oss.str();
Upvotes: 5
Reputation: 311108
You could just write
char a = '1';
char b = '2';
std::string s = std::string( "(" ) + a + "," + b + ")";
Or
char a = '1';
char b = '2';
string s;
for ( char c : { '(', a, ',', b, ')' } )
{
s += c;
}
Here is a demonstrative program.
#include <iostream>
#include <string>
int main()
{
char a = '1';
char b = '2';
std::string s = std::string( "(" ) + a + "," + b + ")";
std::cout << "s = " << s << '\n';
std::string t;
for ( char c : { '(', a, ',', b, ')' } )
{
t += c;
}
std::cout << "t = " << t << '\n';
return 0;
}
The program output is
s = (1,2)
t = (1,2)
Or you could use just a constructor like
std::string s( { '(', a, ',', b, ')' } );
or the method assign
std::string s;
s.assign( { '(', a, ',', b, ')' } );
or append
std::string s;
s.append( { '(', a, ',', b, ')' } );
Here is another demonstrative program.
#include <iostream>
#include <string>
int main()
{
char a = '1';
char b = '2';
std::string s1( { '(', a, ',', b, ')' } );
std::cout << "s1 = " << s1 << '\n';
std::string s2;
s2.assign( { '(', a, ',', b, ')' } );
std::cout << "s2 = " << s2 << '\n';
std::string s3( "The pair is " );
s3.append( { '(', a, ',', b, ')' } );
std::cout << "s3 = " << s3 << '\n';
return 0;
}
Its output is
s1 = (1,2)
s2 = (1,2)
s3 = The pair is (1,2)
Upvotes: 2