Archived

This topic is now archived and is closed to further replies.

gerbenvanderlubbe

Read from a file - beginner question

Recommended Posts

I''m trying to read a file. I''m using this code: ----------------------------------------------- #include <string> struct OPENFILE { FILE* File; void Open(const char* filename) { File = fopen(filename, "r+b"); } void ReadBuffer(void* pBuffer, int buffSize) { int numRead = fread(pBuffer, 1, buffSize, File); } std::string ReadLine() { char currChar; std::string currLine; while(true) //Do until Break is called { ReadBuffer( &currChar, 1 ); if( currChar == ''\0'' || currChar == ''\n'' ) { break; } currLine += currChar; } return currLine; } }; ----------------------------------------------- And then, to read in the file: ----------------------------------------------- OPENFILE File; File.Open("Levels/Map1.map"); MessageBox(0, (const char*)&File.ReadLine(), "The text in the file is:", MB_OK); ----------------------------------------------- But instead of giving the text in the file, the text in the messagebox will be "ÌÌÌÌq" no matter WHAT file I''m reading... How can I solve this... Please help, Gerben

Share this post


Link to post
Share on other sites
JuNC    236
I could be wrong, I don''t really remember the STL stuff, but
you are trying to pass a pointer to a std::string to the
parameter of MessageBox, which is expecting a const char* type.

I think what you want to do is

MessageBox(0, (const char*)File.ReadLine().c_str, "The text in the file is:", MB_OK);

Share this post


Link to post
Share on other sites
taratr98    122
quote:
Original post by JuNC
I could be wrong, I don''t really remember the STL stuff, but
you are trying to pass a pointer to a std::string to the
parameter of MessageBox, which is expecting a const char* type.

I think what you want to do is

MessageBox(0, (const char*)File.ReadLine().c_str, "The text in the file is:", MB_OK);




That is correct. Assuming the original compiled, the second parameter to MessageBox must be a (const char*). You can''t cast a string* directly into a char* and expect it to work - for one thing, a string is not a simple data type like a char* is. So, you''re causing the MessageBox function to read in all kinds of garbage from a string class (who knows exactly what besides the stl programmers).

There is a member function of the string class String.c_str() which creates for you a standard "c-style" string (char *). The function he wrote above properly casts this for use in the messagebox function.

-ATR-

Share this post


Link to post
Share on other sites