Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getline ignoring first character of input

Tags:

c++

arrays

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?

like image 667
lisovaccaro Avatar asked Jun 09 '13 04:06

lisovaccaro


People also ask

Does Getline ignore leading whitespace?

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.

Can you use Getline for 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.

How do I use CIN ignore?

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.

Why does C++ Getline skip?

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.


2 Answers

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'.

like image 164
Amit Avatar answered Oct 10 '22 02:10

Amit


Just remove cin.ignore();

This ignores the first character, thus you miss the 'J'.

like image 34
someone Avatar answered Oct 10 '22 04:10

someone