how do you turn a char into a string with a length of one

how do you turn a char into a string with a length of one?
You can't. You can construct a string of length one from a char though - depending on what kind of string you mean.

1
2
3
char c = 'a';
char  str1[] = {c,'\0'}; //c string
std::string str2(1, c); //c++ string 
Last edited on
These also work:

C++
 
char c = 'A';
1
2
3
// assignment method
string s;
s = c;
1
2
// construction method
string s = c;


C
 
char c = 'A';
1
2
3
/* assignment method 1 (works once) */
char a[ 2 ] = { 0 };
strncpy( a, &c, 1 );
1
2
3
/* assignment method 2 (works any number of times) */
char a[ 2 ];
strncpy( a, &c, 1 )[ 1 ] = 0;
1
2
/* construction method (C99 only)*/
char a[] = { c };

Hope this helps.
Topic archived. No new replies allowed.