You are not logged in.

#1 2004-10-19 02:57:43

dadexter
Member
From: Dorval, QC, Canada
Registered: 2004-09-07
Posts: 274
Website

Need C++ help

Hey guys... I need help with C++... can't seem to find an answer...

I have the following function in a program

void KMeste::slotOpen() {
  ifstream fp;
  char *str;
  QString filename = KFileDialog::getOpenFileName(QString::null, "*", this, "fileopen");
  fp.open(filename.ascii());
  while(fp) {
    fp.getline(str, 512);
    mesteedit->append(str);
  }
}

the problem is that whenever the EOF is reached, the program crashes. I also had the following code before:

void KMeste::slotOpen() {
  // cout << "slotOpen()" << endl;
  fstream fp;
  char *str;
  QString filename = KFileDialog::getOpenFileName(QString::null, "*", this, "fileopen");
  fp.open(filename.ascii());
  while(!fp.eof()) {
    fp.getline(str, 512);
    mesteedit->append(str);
  }
}

and I had the same problem...

Can anyone help me with reading lines from a simple text file?

thanks

Offline

#2 2004-10-19 03:25:38

whatah
Member
Registered: 2003-08-10
Posts: 114

Re: Need C++ help

you can try something like

ifstream fp;
string str;
if (fp.open("file") != -1) {
while (getline(fp, str))
}

however, that won't read only the first 512 chars, if you want only the 512 chars you can do str = str.substr(0, 512) in the while loop.[/code]

Offline

#3 2004-10-19 06:23:39

rehcra
Member
From: Distant galaxy
Registered: 2004-09-15
Posts: 120
Website

Re: Need C++ help

dadexter wrote:
  while(fp) {
    fp.getline(str, 512);
    mesteedit->append(str);
  }

One of the problems seems to be the order of instructions in the loop.
Try to think how computer will run your code: first it will check for EOF ("while(fp)"). Then it will run "getline". (*) And then "append".
But after (*) there could be EOF! So your string could not be set.
You should have:

  while(true) {
    fp.getline(str, 512);
    if (!fp) break;
    mesteedit->append(str);
  }

Why your code crashes is another kettle of fish. The "str" pointer is not initialized. You should have:

char str[512];

instead of

char *str;

http://pdfinglis.tripod.com/widget.html
"In order to make an apple pie from scratch, you must first create the universe."
                                 -- Carl Sagan, Cosmos

Offline

#4 2004-10-19 11:13:53

dadexter
Member
From: Dorval, QC, Canada
Registered: 2004-09-07
Posts: 274
Website

Re: Need C++ help

damn... thanks rehcra

works fine smile

Offline

Board footer

Powered by FluxBB