I'm reading input from a file using an ifstream. The program doesn't seem to read any characters but continually returns eof no matter what file I use. Even when I do ifstream.open(filename) nothing changes. This program is intended to be the lexical analyzer of a compiler, so symbols are returned to indicate what kind of input is in the file.
#include "lex.h"
#include <cstlib>
#include <iostream>
#include <fstream>
//other functions
char Lex::getChar(){
ifstream input;
char token;
if(!input.eof()){
if(token=='#'){ //To indicate when a comment has been reached.
input >> token;
while(token!= '#'){ //To detect end of comment.
input >> token;
}
input >> token;
return token;
}
return token;
} else {
return'$'; //This is returned to indicate end of file.
}
return NULL; //Only placed to compile. This will never be reached.
}
I'm sure I messed up the initialization of the ifstream somehow. Any help would be greatly appreciated.
You must first open the ifstream object before trying to use eof(); method. Also, make sure you set the get pointer to the beginning of the file for certainty. You can use the seekp(); method.