Why are you using the C way to read a file and store it's contents? Why not use std::strings, that would solve all your problems!
#include <string>
#include <fstream>
#include <iostream>
using namespace std;
[.....]
string str_read;
ifstream fin("file.txt");
if (fin.is_open())
cin >> str_read;
else cout << "couldn't open file";
Nick Evan
Not a Llama
10,112 posts since Oct 2006
Reputation Points: 4,142
Solved Threads: 403
because shifting left and right have nothing to do with I/O.
Ah, you have a 'C' mind, not a C++ ;)But if that will solve my problem I guess I'd give it a go, but why exactly would it solve my problem?
Because it makes life easier. You won't have to throw pointers around to each function, but you could just use the entire string. Also thing like strcmp() and strcpy() can be replaced by the '==' and '=' operator.
std::string str = "abc";
if (str == "abc") str = "blablabla";
Nick Evan
Not a Llama
10,112 posts since Oct 2006
Reputation Points: 4,142
Solved Threads: 403
The buffer next_room_script[] lives in the scope of the containing if() block. Your problem will go away if you change the m_nextRoomScript to be a std::string because the string will copy and hold the data you have read from the file. The pointer version just points to the temporary buffer and gets garbled.
mitrmkar
Posting Virtuoso
1,809 posts since Nov 2007
Reputation Points: 1,105
Solved Threads: 395
Right... I thought it might be something like that....
So basically when I pass a char array to a function that takes a pointer, I'm taking the address of the array, which goes out of scope at the end of the if block. If I were to use a string, I would be copying the actual data to a new memory location, not just copying the memory location, right? Now, if I did that, would I need to change the data type of m_nextRoomScript to string, or would there be a way to still keep that as a char*?
I think you've understood it now. I'm guessing that you desire to have the char* in order for to write the data to a file or compare it (using strcmp())... you can very well use a std::string and wherever you need a const char * to the data held by the std::string, you can use the std::string' c_str() function which returns a const C-style string.
Trying to make this clearer ...
void function()
{
char regular_arr[20]= "abc";
std::string std_string = regular_arr; // copies the 'abc' into the string
if(0 == strcmp(regular_arr, std_string.c_str()))
{
// the strÃngs are identical, do something ...
}
FILE * fp = fopen("a.txt", "w");
if(fp)
{
// write the string to file
fputs(std_string.c_str(), fp);
}
}
mitrmkar
Posting Virtuoso
1,809 posts since Nov 2007
Reputation Points: 1,105
Solved Threads: 395