Derek H
Derek H

Reputation: 31

Using cin.ignore() to skip over 2 spaces

I figured out how to use cin.ignore() to ignore until the first space. Example would be

cout << "Enter your name: ";
cin.ignore(256, ' ');

If you enter John Smith, it only reads Smith. But lets say someone wanted to do first, middle, and last name? Like John Doe Smith? Is there a way to ignore until the second whitespace?

EDIT: To clarify, I need each part of the name in a separate variable, not the whole line.

Upvotes: 0

Views: 1878

Answers (1)

Alessandro Scarlatti
Alessandro Scarlatti

Reputation: 734

No need to use ignore. cin stops reading at whitespace by default.

using namespace std;

string firstName = "";
string middleName = "";
string lastName = "";

cin >> firstName;
cin >> middleName;
cin >> lastName;

And as advised above, it is much safer not to ignore input. Use std::getline() instead.

Upvotes: 2

Related Questions