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

Ama*_*ani 3 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;
}
Run Code Online (Sandbox Code Playgroud)

当执行到达getline(cin,rp.command)时,程序仅打印“ Enter repo command:”,并跳过getline(cin,rp.command)行,以使用户没有时间响应。可能是什么问题?

Joh*_*son 6

重复的问题在这里回答

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

您可以使用cin.ignore()来摆脱那些多余的字符getline()


归档时间:

查看次数:

8219 次

最近记录:

11 年,4 月 前