C++ iostream: Using cin >> var and getline(cin, va

2019-02-19 12:12发布

I'm creating a simple console application in C++ that gets string and char inputs from the user. To make things simple, I would like to use the string and char data types to pass input from cin to.

To get string inputs, I'm using the getline method:

string var;
cin.ignore(); //I used ignore() because it prevents skipping a line after using cin >> var
getline(cin, var);

To get char inputs, I'm using the cin >> var method:

char var;
cin >> var;

This works fine for the most part. However, when I enter a string using getline, it ignores the first character of my string.

Is it possible to use getline and cin >> without having to use ignore, or a method I can call to ensure that my first character isn't skipped?

This is a full sample of code where I use both getline and cin >>:

string firstName;
string lastName;
char gender = 'A';

cout << "First Name: ";
cin.ignore();
getline(cin, firstName);


cout << "Last Name: ";
cin.ignore();
getline(cin, lastName);

while(genderChar != 'M' && genderChar != 'F')
{
    cout << "Gender (M/F): ";
    cin >> genderChar;
    genderChar = toupper(genderChar);
}

4条回答
叼着烟拽天下
2楼-- · 2019-02-19 12:25

ignore() does not skip a line, it skips a character. Could you send example code and elaborate on the need for cin.ignore()?

查看更多
我只想做你的唯一
3楼-- · 2019-02-19 12:43

cin>>var;

only grabs the var from the buffer, it leaves the \n in the buffer, which is then immediately grabbed up by the getline

So, following is just fine, (if I understood correctly your problem)

cin>>var;
cin.ignore();     //Skip trailing '\n'
getline(cin, var);

As per your edited post

You don't have to use cin.ignore(); for geline

This extracts characters from buffer and stores them into firstName or (lastName) until the delimitation character here -newline ('\n').

查看更多
Lonely孤独者°
4楼-- · 2019-02-19 12:43

You are using std::isstream::ignore() before std::getline(). std::cin.ignore() will extract the first character from the input sequence and discard that.

http://www.cplusplus.com/reference/istream/istream/ignore/

查看更多
【Aperson】
5楼-- · 2019-02-19 12:49

std::cin.ignore() will ignore the first character of your input.

For your case, use std::cin.ignore() after std::cin and then getline() to ignore newline character as:

cin>>ch;
cin.ignore();  //to skip the newline character in the buffer
getline(cin,var);
查看更多
登录 后发表回答