: : : : It turns out that a string cannot be used, it needs to be a char* type.
: : : : Is there a simple function somewhere that can take a string as a parameter and return a char*?
: : : :
: : : : Cheers.
: : : :
: : :
: : :
: : : If you check the string class in your C++ book (you have one, right?),
: : : it should tell you to use string::c_str();
: : :
: : : For example:
: : :
: : : string str = "hello world";
: : : printf("%s",str.c_str());
: : :
: : I'm not trying to print it to the screen. I need a char* variable. But
:
:
: Yes... now look at the code I wrote and think about what it does.
: str.c_str() returns a char*, I am simply passing it to printf() instead of letting a pointer point at it.
:
:
Technically it returns a const char * and you also need to be carefull you don't modify the string in between the point where you call the c_str member function and where you actually use the data at the address returned from that call or the pointer may be invalidated.
string str = "Hello";
const char * ptr = str.c_str();
cout << ptr << endl; // OK, ptr still points to valid address
str += " world!"; // str has been modified, previous address
// returned by c_str might not be any good
cout << ptr << endl; // Not OK, ptr's address may have been invalidated
If you are trying to open a file using a string, you simply call the c_str member function in the constructor for the file stream object or the open call.
string fname("myfile.txt");
ofstream output(fname.c_str());
or...
string fname("myfile.txt");
ofstream output;
...
output.open(fname.c_str());
or if you wanted to use C FILE pointers for some reason...
string fname("myfile.txt");
FILE * output = fopen(fname.c_str(),"w");