Hi, my name is Thiago May Bitencourt.
I'm learning c++ based on book c++ primary Plush. I'm just a beginner trying to get some knowledge.
I'm having problem with the cin.getLine() function and arrays.
So, I have two arrays with 10 positions and i want to read a person's first name and then its last name (only an example).
Here is some code:
1 2 3 4 5 6 7 8 9 10 11
|
char firstName[10];
char lastName[10];
cout << "First name: ";
cin.getline(firstName, 100);
cin.get();
cout << "Last name: ";
cin.getline(lastName, 100);
cout << "first: " << firstName << endl;
cout << "last: " << lastName << endl;
|
I know that the first argument to the getLine function is the target to the data and the second argument is the maximum number of characters to be read. In the previous code, the getLine function allows me to insert more characters than the variable can hold.
When this happens, the first array uses part of the second array to hold the data (because it's next in the memory, i think). So, when the last name is inserted it overwrites these parts of the first name. Always that i try to show the first array it gets part of the first name (that the variable could hold) plus the last name entirely.
Entrance:
1 2 3
|
First name: Thiago Bitencourt
<Enter>
Last name: Something
|
Result:
1 2
|
first: Thiago BitencourSomething
last: Something
|
I know this is happening because the last name overwrites the 't' and the '\0' from the first name. Then, to show the first name actually shows either the first as the last, because it lost the end-of-string ('\0') element.
But, my question is: How can i avoid this? And, isn't it a security failure? Maybe the compiler should not allow this kind of statement?
Happy with any help ;D