Getline ignoring first character of input

2020-01-29 16:19发布

问题:

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?

回答1:

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



回答2:

Just remove cin.ignore();

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



回答3:

I had this piece of code with the problem that it was eating the first character after the first cycle (first cycle was ok)

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

Output was:

command:> pos

cin= pos

command:> pos ... from 2nd loop it started to delete the 1st character

cin= os

...

If "cin.ignore();" was commented then it resulted in a "segmentation fault":

command:> cin=

Segmentation fault

Solution working for me:

To move the "cin.ignore();" line just 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);

Output was:

command:> pos

cin= pos

command:> pos

cin= pos

...

...

P.S. It was incredible hard to put code here... I am disappointment to continue collaborating.



标签: c++ arrays