Computer Chess Club Archives


Search

Terms

Messages

Subject: Re: OT: C++ code question.

Author: Rémi Coulom

Date: 02:25:49 11/06/03

Go up one level in this thread


On November 06, 2003 at 05:03:32, macaroni wrote:

>in trying to get a book to load from a file, I have had endless trouble. I'm
>using dev-cpp, heres a code snip
>
>
>
>#include <iostream.h>
>#include <fstream.h>
>
>int main()
>{
> int BookSize=0,x;
> char *BookLines[50000];

You declare 50000 char pointers, but they point to nowhere.

> ifstream in("SEEBook",ios::in| ios::binary);

Why ios::binary? If the book is in text mode, then you should not use
ios::binary. (it does not matter for your problem, anyway).

> if (!in)
> {
>  cout << "Book not found!\n";
>  return 1;
> }
> while(in.getline(BookLines[BookSize],120))

This crashes because your pointers point to nowhere. If you really want to do it
this way, you should do a
BookLines[BookSize] = new char[120];
before, or something of that kind. But this would be ugly C++. A nicer way to
handle this would be to declare
std::string BookLines[50000];
or even better,
std::vector<std::string> BookLines;
and let it grow as needed (no magic number anywhere).

> {
>  BookSize++;
> }
> in.close();

in.close() is not necessary: in's destructor does it.
You code looks very much like you are using C++ to do C programming.

> cin >> x;
> return 0;
>}
>
>the program compiles quite happly, and then 'causes an illegal operation', all I
>want it to do is load the file line by line into BookLines. Each line,
>incrementing BookSize so it puts it into the next slot. Any idea's what is
>wrong. Could it be the computer?
>cheers
>tor



This page took 0.01 seconds to execute

Last modified: Thu, 15 Apr 21 08:11:13 -0700

Current Computer Chess Club Forums at Talkchess. This site by Sean Mintz.