I'm just starting with arrays in C++ and I'm having a problem getting the first character of an array.
This is my code,
1- I enter a name, such as "Jim"
char name[30];
cin.ignore();
cin.getline(name, 30);
2- Right away I try to cout the array
cout<<"NAME:"<<name; // THIS PRINTS 'im'
I was sure it would print 'J'. What am I doing wrong?
The getline() function in C++ is used to read a string or a line from the input stream. The getline() function does not ignore leading white space characters.
The C++ getline() is a standard library function that is used to read a string or a line from an input stream. It is a part of the <string> header. The getline() function extracts characters from the input stream and appends it to the string object until the delimiting character is encountered.
The cin. ignore() function is used which is used to ignore or clear one or more characters from the input buffer. To get the idea about ignore() is working, we have to see one problem, and its solution is found using the ignore() function.
It is not the getline() function skipping, cin in responsible for it. When you take any input using cin, it stores '\n' in buffer. Since, getline does not ignore leading whitespace, it thinks it has finished reading and stops reading any further. So, this problem arises when getline() is used after cin statement.
Here is signature of cin.ignore:
istream& ignore (streamsize n = 1, int delim = EOF);
So if you call ignore function without any parameters, it will ignore '1' char by default from input. In this case it ignored 'J'. Remove ignore call and you will get 'Jim'.
Just remove cin.ignore();
This ignores the first character, thus you miss the 'J'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With