SMcCK
SMcCK

Reputation: 155

What is the advantage of using gets(a) instead of cin.getline(a,20)?

We will have to define an array for storing the string either way.

 char[10];

And so suppose I want to store smcck in this array. What is the advantage of using gets(a)? My teacher said that the extra space in the array is wasted when we use cin.getline(a, 20), but that applies for gets(a) too right?

Also just an extra question, what exactly is stored in the empty "boxes"of an array?

Upvotes: 1

Views: 656

Answers (2)

secretgenes
secretgenes

Reputation: 1290

gets() is a C function,it does not do bounds checking and is considered dangerous, it has been kept all this years for compatibility and nothing else.

You can check the following link to clear your doubt :

http://www.gidnetwork.com/b-56.html

Don't mix C features with C++, though all the feature of C works in C++ but it is not recommended . If you are working on C++ then you should probably avoid using gets(). use getline() instead.

Upvotes: 1

mvccouto
mvccouto

Reputation: 11

Well, I don't think gets(a) is bettet because it does not check for the size of the string. If you try to read a long string using it, it may cause an buffer overflow. That means it will use all the 10 spaces you allocated for it and then it will try to use space allocated for another variables or another programs (what is going to make you publication crash).

The cin.getline() receives an int as a parameter with tells it to not read more than the expected number of characters. If you allocate a vector with only 10 positions and read 20 characters it will cause the same problem I told you about gets().

About the strings representation in memory, if you put "smcck" on an array

char v[10];

The word will take the first 5 positions (0 to 4), the position 5 will be taken by a null character (represented by '\0') that will mark the end of the string. Usually, what comes next in the array does not matter and are kept the way it were in the past.the null terminated character is used to mark where the string ends, so you can work it safely.

Upvotes: 0

Related Questions