jose@CSSERVER.CS.MSSTATE.EDU (Jose Cordova) (02/08/90)
I am having trouble using the 'get' method for the 'istream' class.
It generates a 'Segmentation fault' error at run-time. I know the
'istream' is being opened correctly because reading into a 'String'
object with >> works fine. Am I doing something wrong ?
The sample program and "data" illustrate the point:
main()
{
istream from("data",io_readonly,a_useonly);
char *line;
from.get(line,15);
cout << line;
}
Sample "data" file contents:
word1 word2
word3
Other relevant information:
SunOS 4.0.3 libg++ version 1.35.0 g++ version 1.35.0
Jose Cordova, CS Dept., Mississippi State Univ., jose@larry.cs.msstate.edu
dl@G.OSWEGO.EDU (Doug Lea) (02/08/90)
> I am having trouble using the 'get' method for the 'istream' class. > It generates a 'Segmentation fault' error at run-time. I know the > 'istream' is being opened correctly because reading into a 'String' > object with >> works fine. Am I doing something wrong ? > The sample program and "data" illustrate the point: > > main() > { > istream from("data",io_readonly,a_useonly); > char *line; > > from.get(line,15); > cout << line; > } > > Sample "data" file contents: > word1 word2 > word3 > There are 3 istream functions for reading char*'s istream& get (char* s, int n, char terminator = '\n'); istream& getline(char* s, int n, char terminator = '\n'); istream& gets (char **s, char terminator = '\n'); The first two *require* an allocated char* (they differ only in how the trailing terminator is handled.) To use them, you must supply either a char[N] or an allocated char*. The third automatically allocates space for you, that you should later delete. For example, main() { istream from("data",io_readonly,a_useonly); char *line = new char[16]; // enough for string + null char line2[16]; char* line3 = 0; // `= 0' so delete'able even if never allocated -- // Not necessary in this example. from.get(line,15); from.get(line2,15); from.gets(&line3,15); // pass in the addr of line3 cout << line; cout << line2; cout << line3; delete line; delete line3; } Using the String class is a very good way to avoid dealing with these kinds of char* allocation and semantics issues. -Doug