Unable to open file with fstream. it always seems to jump to the else statement and gives me the error message "Error: can't open input file ". I have included in the header file

#include <iostream>
#include <fstream>
#include <sstream>

and in the class file i have the following code and yes i do have a txt file called studentFileName.txt in the same directory.

void StudentRecord::addFile(const string& studentFileName){   
   ifstream infile;
   infile.open ("studentFileName.txt");
   if (infile.is_open()){
      string line, word, StudentName, ProgramCode;
      while(getline(cin, line)){
         istringstream stream(line);
         while (stream >> word) {
            int i = 0;
            if (i % 2 == 0) {
	StudentName = word;
            }
            else {
	ProgramCode = word;
            }
            StudentRecord::add(StudentName, ProgramCode);
         }
      }
      infile.close();
   }
   else {
      cout << "Error: can't open input file " << endl;
   }
}

Any solutions would be greatly appreciated as i am completely stumped.

Thankyou

The file is not in the current directory. If you are using MS-Windows then use Explorer to verify the location of the file and add the full path to the filename. infile.open ("c:\\MyFolder\\studentFileName.txt");

Someone on another forum solved this one for me

Maybe try this:

infile.open(file.c_str());

substitute file for your file.

I ran into this problem and none of the above solved the problem. It was because I was copy pasting the full path from the file security tab. This adds extra formatting code that doesn't show unless you mouse over. Typing the full path manually, instantly fixed the issue.

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.