Home>

If i read or write CString as shown below, an error will occur at the end of the program.
I'd like to avoid this error, but I'm not sure.

* We are not looking for other input/output methods.

CString w_str ("string");
CString r_str;
std :: stringstream st;
std :: iostream&io (st);
int size = w_str.GetLength () * sizeof (TCHAR);
io.write ((const char *)&w_str, size);
io.read ((char *)&r_str, size);

error contents

  • Answer # 1

    #include 
    #include<sstream>
    #include<iostream>
    using tstringstream = std :: basic_stringstream<TCHAR, std :: char_traits<TCHAR>, std :: allocator<TCHAR >>;
    using tostream = std :: basic_ostream<TCHAR, std :: char_traits<TCHAR >>;
    using tistream = std :: basic_istream<TCHAR, std :: char_traits<TCHAR >>;
    int main ()
    {
        CString w_str ("string");
        CString r_str;
        int size = w_str.GetLength () + 1;
        tstringstream s;
        tostream&os (s);
        os.write (w_str.GetString (), size);
        tistream&is (s);
        is.read (r_str.GetBuffer (size), size);
        r_str.ReleaseBuffer ();
        return 0;
    }

    Character setWhen the setting is UNICODEstringstreamIf it's okay if the characters are garbled, the following will also pass ...

    #include 
    #include<sstream>
    #include<iostream>
    int main ()
    {
        CString w_str ("string");
        CString r_str;
        int size = (w_str.GetLength () + 1) * sizeof (TCHAR);
        std :: stringstream s;
        std :: ostream&os (s);
        os.write ((const char *) w_str.GetString (), size);
        std :: istream&is (s);
        is.read ((char *) r_str.GetBuffer (size), size);
        r_str.ReleaseBuffer ();
        return 0;
    }

  • Answer # 2

    There is no problem with std :: string, but is there any reason you want to use CString?

    #include 
    #include<sstream>
    #include<string>
    #include<iostream>
    int main () {
      CString w_str ("string");
      CString r_str;
      std :: string w_str_ = w_str;
      std :: stringstream s;
      s<<w_str;
      std :: string r_str_;
      s >>r_str_;
      r_str = r_str_.c_str ();
      std :: cout<<'['<<r_str<<"] \ n";
      return 0;
    }