Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ convert from 1 char to string?

Tags:

c++

casting

People also ask

Can you convert char to string in C?

Given a string str and a character ch, this article tells about how to append this character ch to this string str at the end. Use the strncat() function to append the character ch at the end of str. strncat() is a predefined function used for string handling.

How do you convert this char array to string in C?

Approach: Get the character array and its size. Declare a string (i.e, an object of the string class) and while doing so give the character array as its parameter for its constructor. Use the syntax: string string_name(character_array_name);

Can you display a single character as a value?

Can you display a single character as a value? Select an answer: Yes, by changing the printf() function's placeholder from %c to %d.


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.


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;

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};