FSTREAM having user input a file name

I have this, this code has a hardcoded file name that will write information to it. How can I modify this so the user specifies the file name? I'm reading my book it's something like: create a variable string, prompt user, read it in, filename.c_str( all of these peices but I can't seem to figure it out.



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
26
27
28
29
30
31
32
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;

int main()
{

	ofstream outClientFile ("a file name .txt");

	//error checking
	if (!outClientFile)
	{
		cerr << "File could not be opened." << endl;
		exit(1);
	}

	int account; 
	char name [30];
	double balance;

	//read in from cin and then place it into a file

	while (cin >> account >> name >> balance )
	{
		outClientFile << account << ' ' << name << ' ' << balance << endl;
		//cout << "? ";
	} 

	return 0;

}
Include string. Make a new string that can store a files name by user input..

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <string>
using namespace std;

int main()
{

	ofstream outClientFile;
	string fileName;

	cout << "Enter the file name : ";
	cin >> fileName;

	outClientFile.open(fileName.c_str());

	//error checking
	if (!outClientFile)
	{
		cerr << "File could not be opened." << endl;
		exit(1);
	}

	int account; 
	char name [30];
	double balance;

	//read in from cin and then place it into a file

	while (cin >> account >> name >> balance )
	{
		outClientFile << account << ' ' << name << ' ' << balance << endl;
		//cout << "? ";
	} 

	return 0;

}
Topic archived. No new replies allowed.