title: QChar to wchar_t
body: <p>I need to convert a QChar to a wchar_t</p>
  
  <p>I've tried the following:</p>
  
  <pre><code>#include &lt;cstdlib&gt;
  #include &lt;QtGui/QApplication&gt;
  #include &lt;iostream&gt;
  
  using namespace std;
  
  int main(int argc, char** argv) {
  
      QString mystring = "Hello World\n";
      wchar_t myArray[mystring.size()];
  
      for (int x=0; x&lt;mystring.size(); x++)
      {
          myArray[x] = mystring.at(x).toLatin1();
          cout &lt;&lt; mystring.at(x).toLatin1(); // checks the char at index x (fine)
      }
  
      cout &lt;&lt; "myArray : " &lt;&lt; myArray &lt;&lt; "\n"; // doesn't give me correct value
      return 0;
  }
  </code></pre>
  
  <p>Oh and before someone suggests using the .toWCharArray(wchar_t* array) function, I've tried that and it essentially does the same thing as above and does not transfer characters as it should.</p>
  
  <p>Below is the code for that if you don't believe me:</p>
  
  <pre><code>#include &lt;cstdlib&gt;
  #include &lt;QtGui/QApplication&gt;
  #include &lt;iostream&gt;
  
  using namespace std;
  
  int main(int argc, char** argv) {
  QString mystring = "Hello World\n";
  cout &lt;&lt; mystring.toLatin1().data();
  wchar_t mywcharArray[mystring.size()];
  cout &lt;&lt; "Mystring size : " &lt;&lt; mystring.size() &lt;&lt; "\n";
  int length = -1;
  length = mystring.toWCharArray(mywcharArray);
  cout &lt;&lt; "length : " &lt;&lt; length;    
  cout &lt;&lt; mywcharArray;
  
  return 0;
  
  }
  </code></pre>
  
  <p>Please help, I've been at this simple problem for days. I'd ideally like to not use wchar_t's at all but unfortunately a pointer to this type is required in a third party function to control a pump using serial RS232 commands.</p>
  
  <p>Thanks.</p>
  
  <p>EDIT: To run this code you will need the QT libraries, you can get these by downloading QT creator and to get the output in the console you'll have to add the command "CONFIG += console" to the .pro file (in QT creator) or to the custom definitions under properties if using a netbeans project.</p>
  
  <p>EDIT:</p>
  
  <p>Thanks to Vlad below for his correct response:</p>
  
  <p>Here is the updated code to do the same thing but using a transfer char by char method and remembering to add the null termination.</p>
  
  <pre><code>#include &lt;cstdlib&gt;
  #include &lt;QtGui/QApplication&gt;
  #include &lt;iostream&gt;
  
  using namespace std;
  
  int main(int argc, char** argv) {
  
  
      QString mystring = "Hello World\n";
      wchar_t myArray[mystring.size()];
  
      for (int x=0; x&lt;mystring.size(); x++)
      {
          myArray[x] = (wchar_t)mystring.at(x).toLatin1();
          cout &lt;&lt; mystring.at(x).toLatin1();
      }
  
      myArray[mystring.size()-1] = '\0';  // Add null character to end of wchar array
      wcout &lt;&lt; "myArray : " &lt;&lt; myArray &lt;&lt; "\n"; // use wcout to output wchar_t's
  
      return 0;
  }
  </code></pre>