Mayukh Sarkar
Mayukh Sarkar

Reputation: 2625

Is getline is as same as gets?

Okay so my question is simple..

We all know that how bad the gets is in C & hence the advice is to use fgets.

Now in C++ we use std::string s and std::getline(std::cin, s)..Now my question is that does getline() has the same boundary checking issue like gets()..

If yes then for char input[100] & cin.getline(input,sizeof(input)); will work for char array but while using string can I write this?

std::string s; & cin.getline(s, s.capacity()); ...is this appropriate or something else can I write??

Upvotes: 1

Views: 178

Answers (2)

udit043
udit043

Reputation: 1620

get() leaves the delimiter in the queue thus letting you able to consider it as part of the next input. getline() discards it, so the next input will be just after it.

If you are talking about the newline character from a console input,it makes perfectly sense to discard it, but if we consider an input from a file, you can use as "delimiter" the beginning of the next field.

Upvotes: 0

Benjamin Lindley
Benjamin Lindley

Reputation: 103751

No, getline does not have the same issues as gets. The function has a reference to the string, and so can call the string's size and capacity member functions for boundary checking purposes. However, it doesn't need to do that, because it also has access the string's resizing member functions, such as push_back, resize or operator+=, which will handle boundary checking automatically, reallocating when necessary.

Upvotes: 5

Related Questions