[galib] Please help!! about get population to CString

Nate Barney barney at chgr.mc.vanderbilt.edu
Mon Dec 15 12:33:27 EST 2003

On Sat, 2003-12-13 at 04:39, cos-mos at maildozy.com wrote:
> I have problem about how to convert individual() in Class GAPopulation() ga
> because  returntype of    ga.individual()  is  GAGenome&  it can't convert to 
> CSstring . My individual() (I use 1DBinaryString)  So If anybody  know how to 
> modify class . Please mail to me . 
> EX  : my individual()  have 110010  and I want it into  "110010" because I want 
> to cut string to use in my project.


One way to do this is to use std::ostringstream.  It's been a while
since I've dealt with MFC, so I'm fuzzy on the details of CString, but i
can get you as far as a const char *, and I imagine you can take it from
there.  (Note: This may or may not compile on your system, depending on
your compiler version.  If you have trouble with this, let me know what
version your compiler is, and I'll try to help.)

1) You need to include the standard header <sstream> (no .h).

    #include <sstream>

2) In the function where you want to convert the GAGenome& to a CString,
declare a variable of type std::ostringstream.  (If you use the std
namespace at the beginning, the type is simply ostringstream.)

    std::ostringstream s;

3) Insert the genome into s, just as you would with cout, or any other

    s << ga.statistics().bestIndividual();

4) To get the std::string representation, one calls the function
std::ostringstream::str().  To get a const char * representation of a
std::string, one calls std::string::c_str().  Given the const char *,
I'm sure you could construct a CString from that.

    s.str().c_str() // use this to make CString

Hope this helps!

More information about the galib mailing list