0

hello everyone,

I am having a major problem with this assignment that asks to create a function whose input is a reference to an input file, which asks user to enter a file name to open for input, then checks to see where the file opened successfully.
the function returns nothing.

I tried implementing the code so far, however for some reason it doesnt even open a file. The file is saved in the same directory as the program. I have know idea whats going on. Please help!

#include<iostream>
#include<fstream.h>
#include<string>
using namespace std;


int main()

{
    ifstream inFile;
    string inFileName;


    cout << "Enter a filename: ";
    cin >> inFileName;


inFile.open(inFileName.c_str());


system ("pause");
return 1;
}
3
Contributors
2
Replies
3
Views
4 Years
Discussion Span
Last Post by Karkalash
1

You can use the is_open() function on the ifstream. As so:

#include<iostream>
#include<fstream.h>
#include<string>
using namespace std;

int main()
{
    ifstream inFile;
    string inFileName;

    cout << "Enter a filename: ";
    cin >> inFileName;

    inFile.open(inFileName.c_str());

    if( ! inFile.is_open() ) {
        cout << "File could not be opened!" << endl;
    } else {
        cout << "File was successfully opened!" << endl;
    };

    system ("pause");
    return 1;
}
1

Right now you only open the file and do nothing with it. You need to check if the file even exists first. Try adding this on line 19

if (!inFile)
    {
        cout << "ERROR 404: FILE NOT FOUND!!";
    }

And then you have to close the file once you're done reading it.

inFile.close();

If you want to learn more see here

http://www.cplusplus.com/doc/tutorial/files/

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.