Mail Archives: djgpp/1998/01/15/10:11:25
Hi!
In your program you use a couple of pointers that isn't properly
initialized.
You must allocate memory for these pointers (look at the code at the
bottom of this message).
getline() writes to a buffer you must provide a pointer to.
However this is a common mistake by new programmers.
(I have also made one of these.)
Using a pointer with out initializing it first can produce nasty results
such as the computer locking up and you need to reboot.
Sincerely yours,
Trond Endrestøl.
My proposal for your code:
#include <fstream.h>
int main()
{
ifstream inFile = "test3.dat"; // test3.dat contains 2 lines for input
if (!inFile) {
cerr << "Error occured during opening of file test3.dat.\n";
return 1;
}
// allocate memory using the new operator:
char *ptr_line1 = new char[51];
char *ptr_line2 = new char[51];
inFile.getline(ptr_line1,50,'\n');
inFile.getline(ptr_line2,50,'\n');
cout << ptr_line1 << endl;
cout << ptr_line2 << endl;
// return allocated memory, although we are just about to exit:
delete[] ptr_line1;
delete[] ptr_line2;
// close inFile:
inFile.close();
return 0;
}
______________________________________________________
Get Your Private, Free Email at http://www.hotmail.com
- Raw text -