[prog] stream eof problem

Robert J. Hansen rjh at sixdemonbag.org
Sun Mar 9 15:28:50 EST 2003


> What makes this most confusing is that when I use the bloodshed compiler
> for windows, it seems to work.  I use the g++ compiler for Linux.

Neither of them should work: there are a couple of bugs in the code
which keep it from being ANSI conformant.  I'll go over a couple of
design suggestions here, and will go over the code more extensively to
try and track down your bug.  I think I already know where it is, but I
want to make sure before I go about embarassing myself on a public
mailing list.  :)

> #include<iostream.h>
> #include<fstream.h>
> #include<string.h>

The .h suffixes are deprecated.  Use

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

... instead.

> struct ITEM {
> 	char  item_code[8];

This should probably be a std::string, not a char[8].  It gives you more
flexibility at very little increased cost.  std::strings are the
preferred C++ way of handling strings; char pointers and arrays are
available mostly to support C legacy code, not for new C++ code.

> void main(){

Not ANSI, and no C++ compiler should allow this to work without raising
a big red warning message.  According to ANSI, the return type of main()
_must_ be an int.  No exceptions.

> 	ITEM product[100];

Try std::vector<ITEM> product(100) instead.  You'll need to #include
<vector> in order to use them.  C arrays exist in C++ mostly for
backwards-compatibility with legacy C code.  Pretty much all new C++
code should be written with vectors instead.  It'll save you worlds of
headache later, if/when you need to resize your array.

> 	} // end if-else
> 
> } // end main

Not strictly required by ANSI, but a good idea: return a 0 from main()
if successful, a nonzero on a failure.  If you don't do this, the
compiler will automagically insert a "return 0;" just before it exits
the main() block.




More information about the Programming mailing list