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;
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
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.
精彩评论