0

I am fairly new to programming in C++. For my computer science class, I was assigned a project that displays a menu, allows to user to pick an option, and execute based on the inputted option. Now, when I try to 'load' data from a text, I use .eof() as the condition for my if statement to verify that there is data within the file, and it works. But when there is no data in the file, it does not execute the else statement properly. What am I doing wrong ?? Thank you for the help!!!

(The following is a snippet of my project, mainly the loadData() function I am having trouble with. The error occurs at "else if (inputFile.eof())")

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

void loadData();

int main() {

    loadData();
    return 0;
}

void loadData() {
    ifstream inputFile;
    inputFile.open("data.txt");

    string fileData;
    if (inputFile) {
        //If the file does possess data, it will display the data
        if (!inputFile.eof()) {
            while (inputFile >> fileData) { cout << fileData << endl; }}
        //If it doesn't possess data, an error is displayed along with starting saveData
        else if (inputFile.eof()) {
            cout << "ERROR: there is no saved data";}
    }
    else {
        cout << "ERROR: could not locate save file";
    }
}
C. Tran
  • 17
  • 1
  • 2
    `eof` means "I already tried to read from the file but it failed due to no more data in the file". – M.M Apr 02 '17 at 21:10
  • As an FYI, there's good documentation online on the standard library on [cppreference.com](http://en.cppreference.com/w/). You can usually find a nice, full description of the behavior of functions in the standard library there, including error conditions. – jaggedSpire Apr 02 '17 at 21:20
  • "if (inputFile) {...}" condition is always true. "inputFile" is an object, and 'exists' regardless of the stream state or existence. – 2785528 Apr 03 '17 at 00:49

0 Answers0