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);
   else {
      cout << "Error: can't open input file " << endl;

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


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:


substitute file for your file.

This question has already been answered. Start a new discussion instead.