dimanche 2 avril 2017

The eof() function causes my 'else' statements to not work properly

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";
    }
}

Aucun commentaire:

Enregistrer un commentaire