C++ ifstream extract a series of integers

Description

C++ ifstream extract a series of integers

#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <iostream>
using namespace std;

ifstream& openFile()// w  w w . ja  va  2s .co m
{
    ifstream* pFileStream = 0;
    for(;;)
    {
        string sFileName = "main.cpp";

        pFileStream = new ifstream(sFileName.c_str());
        if (pFileStream->good())
        {
            pFileStream->seekg(0);
            cerr << "Successfully opened " << sFileName << endl;
            break;
        }
        cerr << "Couldn't open " << sFileName << endl;
        delete pFileStream;
    }
    return *pFileStream;
}

int main(int nNumberofArgs, char* pszArgs[])
{
    ifstream& fileStream = openFile();

    while (!fileStream.eof())
    {
        int nValue = 0;
        fileStream >> nValue;

        if (fileStream.fail()){
            break;
        }
        cout << nValue << endl;
    }

    return 0;
}



PreviousNext

Related