You are not logged in.
Pages: 1
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
DaDeXTeR (Martin Lefebvre)
My screenshots on PicasaWeb
[img]http://imagegen.last.fm/dadexter/recenttracks/dadexter.gif[/img]
Offline
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
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
damn... thanks rehcra
works fine
DaDeXTeR (Martin Lefebvre)
My screenshots on PicasaWeb
[img]http://imagegen.last.fm/dadexter/recenttracks/dadexter.gif[/img]
Offline
Pages: 1