C++ convert from 1 char to string?
C++CastingC++ Problem Overview
I need to cast only 1 char
to string
. The opposite way is pretty simple like str[0]
.
The following did not work for me:
char c = 34;
string(1,c);
//this doesn't work, the string is always empty.
string s(c);
//also doesn't work.
boost::lexical_cast<string>((int)c);
//also doesn't work.
C++ Solutions
Solution 1 - C++
All of
std::string s(1, c); std::cout << s << std::endl;
and
std::cout << std::string(1, c) << std::endl;
and
std::string s; s.push_back(c); std::cout << s << std::endl;
worked for me.
Solution 2 - C++
I honestly thought that the casting method would work fine. Since it doesn't you can try stringstream. An example is below:
#include <sstream>
#include <string>
std::stringstream ss;
std::string target;
char mychar = 'a';
ss << mychar;
ss >> target;
Solution 3 - C++
This solution will work regardless of the number of char
variables you have:
char c1 = 'z';
char c2 = 'w';
std::string s1{c1};
std::string s12{c1, c2};
Solution 4 - C++
You can set a string equal to a char.
#include <iostream>
#include <string>
using namespace std;
int main()
{
string s;
char one = '1';
char two = '2';
s = one;
s += two;
cout << s << endl;
}
>./test
12