Reaching End of File too early

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.

Here's the code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#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.
Last edited on
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.

Aceix.
Topic archived. No new replies allowed.