7

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?

Amani
  • 11,038
  • 16
  • 74
  • 118

2 Answers2

10

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().

Community
  • 1
  • 1
Johan Hjalmarsson
  • 3,092
  • 4
  • 36
  • 57
0

There are newline characters in cin's buffer, so getline() takes it as an input from user.

You should flush cin buffer before using getline().

Community
  • 1
  • 1
Wacek
  • 4,246
  • 2
  • 17
  • 28