What is the difference between gets() and cin.getline(). And why gets() is unsafe or bad........ | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

What is the difference between gets() and cin.getline(). And why gets() is unsafe or bad........

file handling

3rd Jun 2017, 12:24 PM
SatanicAngal666
SatanicAngal666 - avatar
3 Answers
+ 3
@Noman Jezzy Welcome.
4th Jun 2017, 3:20 PM
Kinshuk Vasisht
Kinshuk Vasisht - avatar
+ 1
Gets() is a C function, intended to read any number of characters from the stdin (standard input) and assign it to a character array passed to it. Eg- char * buf=new char[10]; gets(buf); puts(buf); Now, there is a problem that gets can accept any number of characters till \n, so even if buf can max have 10 characters, gets can accept any number of characters even if the input has 2000 characters, even in this case. Also, gets doesn't run any memory check to see if the extra data is altering any previously occupied memory. Thus, entering 2000 characters for a 10 character array may alter the memory of other arrays defined in the program. Thus, gets() is unsafe, and must not be used. On the other hand, getline is far safer, as it kindly asks the user for the number of expected character which will be entered, Thus, preventing memory alterations...
4th Jun 2017, 3:17 PM
Kinshuk Vasisht
Kinshuk Vasisht - avatar
+ 1
thanks <3
4th Jun 2017, 3:19 PM
SatanicAngal666
SatanicAngal666 - avatar