Reputation: 13
I'm using C ++ 11. I'm wondering if there are any advantages to using cin.getline ()
compared to gets ()
.
I need to fill a char
array.
Also, should I use fgets
or getline
for files?
Upvotes: 0
Views: 187
Reputation: 206717
I'm wondering if there are any advantages to using cin.getline () compared to gets ().
I am assuming you really mean gets
, not fgets
.
Yes, there definitely is. gets
is known to be a security problem. cin.getline()
does not suffer from that problem.
It's worth comparing fgets
and cin.getline
.
The only difference that I see is that fgets
will include the newline character in the output while cin.getline
won't.
Most of the time, the newline character is ignored by application code. Hence, it is better to use cin.getline()
or istream::getline()
in general. If presence of the newline character in the output is important to you for some reason, you should use fgets
.
Another reason to prefer istream::getline
is that you can specify a character for the delimiter. If you need to parse a comma separated values (CSV) file, you can use:
std::ifstream fstr("some file name.csv");
fstr.getline(data, data_size, ',');
Upvotes: 8
Reputation: 381
Of course.
First of all gets
doesn't check of length of the input - so if the input if longer than char array, you are getting an overflow.
On the other hand cin.getline
allows to specify the size of stream.
Anyway, the consensus among C++ programmers is that you should avoid raw arrays anyway.
Upvotes: 3