Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 301
  • Last Modified:

Problem writing listbox strings to a text file in C++; File contents are numbers instead of strings

Easiest thing in the world: writing strings to a text file that are fetched from a listbox in C++ 6.0(or so I thought).

Here's my code:

#include <iostream>
#include <fstream>
using namespace std;

ofstream myfile;       
myfile.open("C:\MyFile.txt");

m_listBox.GetText(0, strMyString);
myfile << strMyString << endl;
myfile.close();

The file gets created, and is written to.  But when I open the file in windows explorer, instead of seeing the a string in the file, I see a number that looks like a memory address, such as 0034544C.

If I alter the code above, to write string like this:

myfile << "My Test String" << endl;

then the string gets written correctly.

So, the issue is perhaps with the call to the list box's GetText() function.  However, in the debugger, the string variable I pass into the call to GetText() shows a valid string (in both the Watch window and when I mouse hover over the variable).

Any thoughts?

Thanks very much.
0
cjm20
Asked:
cjm20
  • 2
1 Solution
 
jkrCommented:
You are getting the text from yopur list box as a CString, which is not really meaningful for an ofstream - use 'CString::operator LPCTSTR()' (http://msdn.microsoft.com/en-us/library/aa300569%28v=VS.60%29.aspx) to get a string, e.g.
m_listBox.GetText(0, strMyString);
myfile << (LPCTSTR) strMyString << endl;
myfile.close();

Open in new window

0
 
jkrCommented:
BTW, if your project is set to UNICODE, you need to either use a 'std::wofstream' instead or convert the list box data to ASCII if you need that character format, e.g.
m_listBox.GetText(0, strMyString);
char* buf = new char[strMyString.GetLength() + 1];
wcstombs(buf,LPCTSTR) strMyString,trMyString.GetLength() + 1);
myfile << buf << endl;
delete[] buf;
myfile.close();

Open in new window

0
 
cjm20Author Commented:
Perfection.  Simple matter of casting.  Thanks a bunch.
0

Featured Post

Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now