Getline ignores first character input

I am just starting with arrays in C ++, and I have a problem getting the first character of an array.

This is my code,

1- I enter a name, for example "Jim"

char name[30]; cin.ignore(); cin.getline(name, 30); 

2- Immediately I try to disconnect an array

  cout<<"NAME:"<<name; // THIS PRINTS 'im' 

I was sure that he would print "J". What am I doing wrong?

+4
source share
3 answers

Here is the signature of cin.ignore:

 istream& ignore (streamsize n = 1, int delim = EOF); 

So, if you call the ignore function without any parameters, it will ignore the '1' char by default from the input. In this case, he ignored "J". Remove the ignore call and you will get "Jim."

+7
source

Just remove cin.ignore ();

This ignores the first character, so you skip "J".

+3
source

I had this piece of code with the problem that it used the first character after the first loop (the first loop was fine)

 do{ cout << endl << "command:> "; string cmdStr1=""; cin.ignore(); getline(cin, cmdStr1); cout << "cin= " << cmdStr1 << endl; //For Debuging //...more code here }while(1); 

The output was:

command:> pos

cin = pos

command:> pos ... from the 2nd cycle, he began to delete the 1st character

cin = os

...

If "cin.ignore ();" was commented, then this led to a β€œsegmentation error”:

command:> cin =

Segmentation error

The solution works for me:

To move "cin.ignore ();" lines immediately before the do-while loop.

 cin.ignore(); do{ std::cout << endl << "command:> "; std::string cmdStr1=""; std::getline(std::cin, cmdStr1); std::cout << "cin= " << cmdStr1 << endl; //For Debuging //...more code here }while(1); 

The output was:

command:> pos

cin = pos

command:> pos

cin = pos

...

...

PS It was very difficult to put the code here ... I am disappointed that I continue to cooperate.

-1
source

Source: https://habr.com/ru/post/1485248/


All Articles