What does cin.get(ch), cin.ignore(20, ' '), and getline(cin,name) mean in this program?

Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
 #include <iostream>
using namespace std;
int main()
    {char ch;
    string name;
    cout<<"Enter your first name and last name separated by space:";
    cin.get(ch);
    cin.ignore(20,  ' ');
    getline (cin, name);
    cout <<ch<< " "<< name;
        return 0;
}
Hello iamyiyaj,

This may not be a perfect explanation, but here goes.

cin.get(ch); This will get the first and only one character. Even if you type more than one character from the keyboard.

cin.ignore(20, ' '); This will remove the next 20 characters or up to a space which ever comes first from the input buffer. This i more often written as cin.ignore(2000, '\n '); or std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // <--- Requires heder file <limits>.

getline (cin, name); This is the best way to enter a string especially one with a space in the string. This will retrieve everything from the input buffer including the new line character. The new line character will be discarded when stored in a string variable.

Line 10 just shows you what each variable contains.

Hope that helps,

Andy
Registered users can post here. Sign in or register to post.