myfile.open (variable)

I'm getting an error while trying to use a user defined variable, as the filename for myfile.open (variable) - however when I change the variable to a static filename in quotes "filename.txt" it works.

here is the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
	if (responseMenu == 'a') {
		// Create user .txt file and populate with user input
		string userFilename;
		cout << "Please enter a filename for your .txt document." << endl;
		cin >> userFilename;
		cout << endl;
		cout << endl;

	// Create file and accept user input
	ofstream myfile;
	myfile.open (userFilename);
	string input;
	cout << "Please enter the content to be saved into file: " << endl;
	cout << "To save to file and exit, enter semicolon(;)" << endl;
	cout << "This program can save multiple new lines." << endl;
	cout << " " << endl;
	while (input != ";") {
		getline (cin, input);
		myfile << input << "\n";
	}
	myfile.close();


Error message:

1
2
3
1>c:\users\me\documents\visual studio 2008\projects\myworks\newtest\newtest\newtest.cpp(39) : error C2664: 'void std::basic_ofstream<_Elem,_Traits>::open(const wchar_t *,std::ios_base::openmode,int)' : cannot convert parameter 1 from 'std::string' 
.....
\newtest\newtest.cpp(70) : warning C4018: '<' : signed/unsigned mismatch


Anybody, i'm very new to C++ so it's most likely simple.
 
myfile.open (userFilename);


open is expecting const char *, not a string. string does not provide an automatic conversion to const char *. You need to do the following:
 
myfile.open (userFilename.c_str());


Thanks, works great.
Anon. How come I can use a string as a filename?

Here's my code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
bool saveToFile( std::string &in )
{
	//Create a sdt::string for user input, for the filename.
	std::string fileName = "";

	//Output a message and then get user input.
	std::cout << "\n\n\tPlease enter a filename to save to:\n\tFilename: ";     

	std::getline( std::cin, fileName, '\n' );

	//Create an outfile to save to.
	std::ofstream oFile;
	oFile.open( fileName + ".txt", std::ios::out );

	if( oFile.is_open() )
	{
		//code...

		return true;
	}
	else
		std::cout << "\n\tSaving to file failure.\n\n";

	return false;
}
Lynx876 wrote:
How come I can use a string as a filename?

Your compiler is new enough to support this corner of C++11.
Ohhhh right, thanks. Just in case anyone is wondering. I'm using Visual Studio 2012.
Oh, I have Visual Studio 2012, but am using Visual C++ 2008 - Should I be using Visual Studio to write and compile my code?
I, myself, would use the latest. Which I do.

Learn now, what you don't want to have to learn later! lol.
Topic archived. No new replies allowed.