User-defined input file name

Hi everyone, I'm new to this forum and require some assistance.

I have to make a program that reads from a file and prints the first three words from after the first three commas, which I've done.

However, I have to allow the user to define the name of the input file, meaning that the actual name of the file has to dynamically change depending on what the user chooses. As in, if they enter "asdf" when prompted, the file that the C++ program reads from will be named "asdf."

My code so far:
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
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
string filename, after_comma1, after_comma2, after_comma3;

cout << "This program will let the user choose a filename. Then, it will show the first\nword following each of the first three commas in the file." << endl;
cout << "\nPlease enter your desired filename." << endl;
cin >> filename;
filename = filename + ".dat";

ifstream inData;

inData.open(filename);

inData.ignore(200, ',');
	inData >> after_comma1;
	cout << after_comma1 << endl;

inData.ignore(200, ',');
	inData >> after_comma2;
	cout << after_comma2 << endl;

inData.ignore(200, ',');
	inData >> after_comma3;
	cout << after_comma3 << endl;

inData.close();

return 0;
}


Right now, if you enter the name of the input file as it was created, aptly named "input.dat" (you just have to enter the name as "input" ) the program works.

May I get a little help please? Thank you! :)
I think you should learn how to use main function's parameter,such as:

 
int main(int argc, char* argv[])

argv had stored all the input string.
...perhaps, but that doesn't answer his question.

Line 18 should read inData.open(filename.c_str());

Make sure to pay attention to the type of things you need when passing arguments to functions. A const char* and a std::string are two different things.

Hope this helps.
Topic archived. No new replies allowed.