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?
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With