Program keeps closing after the user inputs desired file name

I am trying to write a code that prompts the user for am input file name and opens it to display it's contents. My problem is that when ever the user inputs something, the program closes automatically. I added check points for troubleshooting. I never get to see "inputted" or anything after. Why does it close and how do I get it to stop?

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
40
41
  #include <iostream>
#include <fstream>			//to use files
#include <string>			//to use string objects
using namespace std;

void main()
{
	ifstream f;
	string fileName;	//input from user for the file name
	string str;	//to hold file input
	char input;		//continue to next 24 lines?
	int count = 0;
	int max = 24;

	//open desired file
	cout << "Enter the file you wish to view: ";
	cin >> fileName;

	cout << "inputted";
	f.open(fileName, ios::in);

	cout << "file opened successful";

	//display desired file
	if (f)
	{
		getline(f, str);
		while (f)
		{
			cout << str << endl;
			getline(f, str);
		}
	}
	else
	{
		cout << "ERROR: Could not open the file!";
		return;
	}

	system("pause");
}
Last edited on
It's probably not opening the file, going into your else statement and hitting that return, which then (if you are running from an IDE) might close the terminal.

Get rid of the return so that even if the file doesn't open it will hit the pause.

And your "file opened successful" is in the wrong place sinc eyou haven't checked f yet. It should be in the if.
Topic archived. No new replies allowed.