Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is std::getline() skipped? [duplicate]

Tags:

c++

I have this C++ simple program;

#include <iostream>
using std::endl;
using std::cout;
using std::cin;
using std::getline;

#include <string>
using std::string;


struct Repository
{
    string name;
    string path;
    string type;
    string command;
};


int main()
{
    Repository rp;

    cout << "\nEnter repo name: ";
    cin >> rp.name;

    cout << "Enter repo path: ";
    cin >> rp.path;

    cout << "Enter repo type: ";
    cin >> rp.type;

    cout << "Enter repo command: ";
    getline(cin, rp.command);

    cout << "\nRepository information: " << endl;
    cout << rp.name << "\n" << rp.path << "\n" << rp.type << "\n" << rp.command << endl;

    return 0;
}

When execution reaches getline(cin, rp.command) the program just print "Enter repo command: " and skips the getline(cin, rp.command) line so that the user is not given time to respond. What could be the possible problem?

like image 427
Amani Avatar asked Aug 01 '14 07:08

Amani


Video Answer


1 Answers

Duplicate question answered here.

basically, cin>> doesn't remove new lines from the buffer when the user presses enter. getline() mistakes this for user input along with enter.

You can use cin.ignore() to get rid of those extra characters before using getline().

like image 146
Johan Hjalmarsson Avatar answered Oct 06 '22 16:10

Johan Hjalmarsson