# read a text file and display the content into the list box

This is a discussion on read a text file and display the content into the list box within the Windows Programming forums, part of the Platform Specific Boards category; Hi all, i need to open a text file and display the content in the listbox, i use the following ...

1. ## read a text file and display the content into the list box

Hi all,

i need to open a text file and display the content in the listbox, i use the following code:

Code:
string line;
ostringstream out;
ifstream myfile ("D:\\text.txt");
if (myfile.is_open())
{
while (! myfile.eof() )
{
getline (myfile,line);
out << line << endl;
string line2 = out.str();

CString line3 = line2.c_str();

}
}
but i can't convert const char* into CString , how to do it?

also any other method to read text file into listbox or editbox which is easier?
thx!

2. > while (! myfile.eof() )
Read the FAQ on why using eof() to control a loop is bad.

> but i can't convert const char* into CString , how to do it?
Was that your actual error message?

3. If you have corresponding constructor:
Code:
CString line3(line2.c_str());

4. There's numerous methods, one example below;

Code:

string line;
string pile;
ifstream myfile ("text.txt");
if (myfile.is_open())
{
while (getline(myfile,line,'\0'))
{
pile+=line;
}
}
// utilize string (pile)
If you're only dealing with text files, there's no need to get overly complicated.

5. Your indentation could use a little work too
It works, but it could be better!

6. To convert char * into CString use:

CString mystring;
mystring.Format("&#37;s",pBuf);

To convert back use (LPCSTR)charstring;

7. thanks for reply, now i need to display the content into multiple line just the same as the content in the file, how to do it?
thanks!

8. Well are you getting anything displayed at the moment?

Like is DetailValue.AddString(line3); doing anything at all?

A guess would be that you're seeing one long line, possibly with the occasional black box where each newline should be.

Standard C++ line delimiters are \n, but IIRC the windows APIs need \r\n to mark the end of a line, and cause a linefeed.

9. Well, I'm not 100&#37; sure about it whether accepts \n as newline or not, but it's very easy do call Replace to replace \n with \r\n.

10. should this work?

Code:
if (myfile.is_open())
{
while (getline(myfile,line, '\n'))
{
pile+=line;
pile+='\n';
}
but actually the result is still a line showing all text while my input file has mutilple line...

11. You must add each line to each line in the list box.

IE: Use getline() and use \n as the delimeter. Do this to the end of the file.

Add the string retrieved in getline() to the list box.

Popular pages Recent additions