[comp.lang.c++] get

murison@cfa.HARVARD.EDU (Marc A. Murison, RG) (05/06/91)

/*
 *  iotest.cpp
 *
 *  Why don't getline() and get() work in this program?  
 *  getline() is supposed to read a line of text, including the 
 *  termination character (newline by default). It doesn't 
 *  include the termination character. Meanwhile, get() seems to 
 *  stop working after reading only one line.
 *
 *  Compiler = Borland C++ 2.0
 *
 *  Input is any normal ascii text file, specified on command line.
 *
 *  Any info would be appreciated!
 *
 *  Marc Murison    murison@cfacx2.harvard.edu 
 *                  pepmmu@cfaamp.harvard.edu
 *
 */

#include <fstream.h>
#include <conio.h>        //for kbhit()

const int SIZE = 257;
int setup( int argc, char **argv, fstream &in, fstream &out );

int main( int argc, char *argv[] )
{
    fstream    in, out;
    
    if( !setup( argc, argv, in, out ) )  return 1;

    char buff[SIZE];
    while( in && out ) {

        // When this statement is executed, the newline is
        // not appended to the buffer:
        in.getline( buff, SIZE, '\n' );

        // Here, nothing happens after the 1st line is 
        // read -- the buffer gets a NULL as first byte,
        // causing an infinite loop (thus the need for
        // kbhit()).
//      in.get( buff, SIZE, '\n' );
//      if( kbhit() )  break;

        out << buff;
    }
    in.close();
    out.close();
    
    return 0;
}


int setup( int argc, char **argv, fstream &in, fstream &out )
{
    if( argc != 3 ) {
        cerr << "\nUse:  iotest  infile  outfile\n";
        return 0;
    }

    in.open( argv[1], ios::in );
    if( !in ) {
        cerr << "\a\nUnable to open " << argv[1] << " for input!\n";
        return 0;
    }
    
    out.open( argv[2], ios::out );
    if( !out ) {
        cerr << "\a\nUnable to open " << argv[2] << " for output!\n";
        return 0;
    }
    
    return 1;
}