开发者

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

开发者 https://www.devze.com 2023-01-19 14:29 出处:网络
Why does cin.getline start working for the second line on the body input but break on the first? 开发者_运维知识库

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消