User input file name (FSTREAM)

So I want the user to input the file they wish to open but for some reason after I input the file name "new.txt" it doesnt open. But if I simply write "new.txt" inside the open function it works. How can I make it so the user can type the file they wish to open.

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
   main()
{
	/*Code to test the function AreParanthesesBalanced*/
	string expression;
	string temp;
	string file_name;

	ifstream file;

	cout << "Input the file name you wish to open: ";
   getline(cin, file_name);

	file.open(file_name.c_str());



	while (!file.eof())
    {
        getline (file, temp);
        expression.append(temp);
    }

    file.close();


	if(AreParanthesesBalanced(expression))
		cout<<"Balanced\n";
	else
		cout<<"Not Balanced\n";
}
Have you tried opening a debugger and stepping through your code to see what is happening? You might be able to find out if something strange is occurring.
Do not loop on !eof(). This does not work the way you expect. The eof bit is set true only after you make a read attempt on the file. This means after you read the last record of the file, eof is still false. Your attempt to read past the last record sets eof, but you're not checking it there. You proceed as if you had read a good record. This will result in reading an extra (bad) record. The correct way to deal with this is to put the >> (or getline) operation as the condition in the while statement.
1
2
3
  while (cin >> var) 
  {  //  Good cin or istream operation
  }
Try removing the .c_str() from file.open() statement. The open statement has worked just fine for me with a std::string for the file name. I have also use a #define file_name "afilename" that has worked.
Handy Andy wrote:
Try removing the .c_str() from file.open() statement

That only works if you're on C++11 or later.
Topic archived. No new replies allowed.