tags:

views:

81

answers:

2

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;
+2  A: 

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.

JoshD
I removed both of them and it was the same except it skipped the name input
Will03uk
@Will03uk: I added a bit to my answer. You may want to add a flush.
JoshD
I made the same assertion about flush aq couple of weeks ago, but @anon pointed out that the std::cin is tied to std::cout forcing an automatic flush before std::cin does a read: http://www.cplusplus.com/reference/iostream/ios/tie/
Martin York
@Martin York: Oh, cool. Thanks for the information.
JoshD
Non of this is working??
Will03uk
+3  A: 

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

Alf P. Steinbach
Non of this is working??
Will03uk