Using the ifstream class to extract a series of integers: - C++ File Stream

C++ examples for File Stream:stream

Description

Using the ifstream class to extract a series of integers:

Demo Code

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

ifstream& openFile()/*from  www  .j  av a2s .  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;
}

Result


Related Tutorials