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?
#include <iostream>
#include <fstream> //to use files
#include <string> //to use string objects
usingnamespace 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");
}
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.