mercredi 1 novembre 2017

How do I read the amount of input values from a file input in C++?

In my program, I'll be reading five values from a file that the user specifies. An error message will be displayed if the file does not open or if I get to the end of the file before reading five values. How can I determine if the end of the file is reached before five values are read? Here is my code so far:

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main(){

//variable to define the file stream objects
ifstream infile;
ofstream outfile;

string fileName;

//long long int variables to store the values for each store's sales
long long int store1, store2, store3, store4, store5;

cin >> fileName;
infile.open(fileName.c_str());

//if statement to display error message if the file cannot be opened
if(!infile)
    cout << "File \"" << fileName << "\" could not be opened " << endl;

else
{
    infile >> store1 >> store2 >> store3 >> store4 >> store5;
    cout << store1 << store2 << store3 << store4 << store5;
}


    return 0;
}

Aucun commentaire:

Enregistrer un commentaire