c++ - How to correctly use istream::get ( char* s, streamsize n, char delim ); -
the documentation says:
istream::get ( char* s, streamsize n, char delim ); // extracts characters stream , stores them // c-string array origin @ s i tried analyze function does. takes pointer "by value". cannot allocate dynamic memory , set pointer s it. can alter pointer s points to.
but if function cannot perform dynamic memory allocation, how can homecoming output length not known? how should utilize function? should preallocate memory , pass pointer s , delete myself?
you should preallocate memory (pointed s) of size n, pass s first , n sec parameter of function. way, get read maximum n bytes (including terminating null) , re-create them buffer pointed s
if buffer local (an array on stack, lets say), don't have delete (in fact can't) if dynamic (i.e, allocated new[], malloc, operator new or whatever) have free accordingly.
example:
const int n = 50; char *s = new char[n]; cin.get(s, n); //... delete []s; note: although valid, others commented, improve utilize std::string instead.
c++
No comments:
Post a Comment