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;
}

Recommended Answers

All 2 Replies

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;
}

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/

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.