Will03uk
Will03uk

Reputation: 3444

cin.getline is skipping one line of input and taking the next

Why does cin.getline start working for the second line on the body input but break on the first?

Example Program run:

Enter name: Will
Enter body: hello world
hello again <= It accepts this one



 char* name = new char[100];
 char* body = new char[500];

 std::cout << "Enter name: ";
 std::cin.clear();
 std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
 std::cin.getline(name, 100);

 std::cout << "Enter body: ";
 std::cin.clear();
 std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
 std::cin.getline(body, 500');
 std::cin >> body;

Upvotes: 2

Views: 3374

Answers (2)

JoshD
JoshD

Reputation: 12824

Because you're ignoring the first line with the cin.ignore statement.

std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');

That will ignore a whole line.

Remove that and you'll get what you want.

You may also want to flush the cout stream to assure your output prints to the screen right away. Add a cout.flush(); before your getline.

Upvotes: 2

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145204

As JoshD says, but additionally, you can save a lot of work & pain by using std::string and std::getline from the <string> header.

Like ...

#include <string>
#include <iostream>
int main()
{
    using namespace std;
    std::string name;
    cout << "Enter name: ";  getline( cin, name );
}

Cheers & hth.,

– Alf

Upvotes: 2

Related Questions