• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 305
  • 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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

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