Martin Drozdik
Martin Drozdik

Reputation: 13303

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 from the stream and stores them as a 
// c-string into the array beginning at s

I tried to analyze what this function does. It takes a pointer "by value". That is it cannot allocate dynamic memory and set the pointer s to it. It can only change what the pointer s points to.

But if the function cannot perform dynamic memory allocation, how can it return an output whose length is not known? How should I use this function? Should I preallocate memory and pass the pointer to it as s and then delete it by myself?

Upvotes: 2

Views: 5048

Answers (3)

Hayri Uğur Koltuk
Hayri Uğur Koltuk

Reputation: 3020

You should preallocate memory (pointed to by s) of size n, pass that s to first and n to second parameter of the function. This way, get will read maximum n bytes (including terminating null) and copy them to buffer pointed to by s

If your buffer is local (an array on the stack, lets say), you don't have to delete it (in fact you can't) However if it is dynamic (i.e, allocated by new[], malloc, operator new or whatever) then you have to free it accordingly.

example:

const int n = 50;
char *s = new char[n];

cin.get(s, n);
//...

delete []s;

note: although this is valid, as others commented, better use std::string instead.

Upvotes: 4

Tony The Lion
Tony The Lion

Reputation: 63200

You should use it like this:

const int size = 10;
char s[size]; //large enough to fit string
stream.get(&s[0], size, '\n');

You preallocate the buffer you need and make sure it's large enough to fit target string.

Upvotes: 3

Konrad Rudolph
Konrad Rudolph

Reputation: 545588

The documentation is clear:

stores them as a c-string into the array beginning at s

s has to point to a valid array that’s big enough to accommodate the read string.

how can it return an output whose length is not known

The maximum length is known, it’s n (actually n - 1, since one character is reserved for the null termination of the C string).

However, given your questions it’s probably more appropriate to use the std::string overload of getline.

Upvotes: 5

Related Questions