convert char to string

I read this post:
http://www.cplusplus.com/forum/beginner/4967/

I want to convert a randomly generated char to a string then compare it to a string as a test for a binary search.
I will concatenate the chars to a string from 3 to 10 chars in length.

What is the proper way to convert a char to a string if I am using
#include <string>

This code did not work for me.
 
  string mystring = string(char);
Last edited on
You can't pass a type name to string's constructor. You have to pass an object of type char.
1
2
3
4
 
  char c = 'x';
  string mystring = string(c);
  string mystring = string(1, c);


This can be shortened to simply:
1
2
  string mystring ('x');
  string mystring (1,'x');


Edit: Oops. Didn't double check that before posting. Thanks coder777.
Last edited on
The constructor of string requires a second parameter. See (6):

http://www.cplusplus.com/reference/string/string/string/
Nice post. Thanks for the help!
This is sloppy. I'll clean it up.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>       /* time */
#include <string>
using namespace std;

int main ()
{
   string aword;
  /* initialize random seed: */
    srand (time(NULL));
  int i, randomInt, count = 0;
  char letter;

  bool done = false;

 do  {
    //randomInt = rand() ;
   randomInt = rand() % 26 + 65;

   letter = (char)randomInt;

   string aletter (1,letter);
  //  printf (" %d %c", randomInt, letter);
    count ++;
    if (count == 20){ done = true;}
    if (count % 10 == 0) printf (" \n ");
      cout<<aword<<endl;
      aword = aword + aletter;
  } while (!done);

  return 0;
}


Topic archived. No new replies allowed.