为什么跳过std :: getline()?

时间:2014-08-01 07:01:19

标签: c++

我有这个C ++简单程序;

#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;
}

当执行到达getline(cin,rp.command)时,程序只需打印&#34;输入repo命令:&#34;并跳过getline(cin,rp.command)行,以便用户没有时间回复。可能出现什么问题?

2 个答案:

答案 0 :(得分:5)

Duplicate question answered here

基本上,当用户按Enter键时,cin>>不会从缓冲区中删除新行。 getline()错误地将此与用户输入一起输入。

在使用cin.ignore()之前,您可以使用getline()删除这些额外字符。

答案 1 :(得分:0)

cin缓冲区中有换行符,因此getline()将其作为用户的输入。

在使用getline()之前你应该flush cin buffer

相关问题