【问题标题】:Why is std::getline() skipped? [duplicate]为什么 std::getline() 被跳过? [复制]
【发布时间】:2014-09-24 07:49:50
【问题描述】:

我有这个 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) 时,程序只打印“Enter repo command:”并跳过 getline(cin, rp.command) 行,这样用户就没有时间响应了。可能是什么问题?

【问题讨论】:

  • 你的结构是什么样的?
  • 我们需要查看Repository的定义。
  • 需要更多细节。崩溃怎么办? .command 是什么类型的?
  • @PaulR,添加了结构定义。
  • 上面的代码不应该崩溃,你的问题可能在别处,发布一个显示崩溃的最小可编译示例。

标签: c++


【解决方案1】:

Duplicate question answered here

基本上,cin&gt;&gt; 在用户按下回车时不会从缓冲区中删除新行。 getline() 将其误认为是用户输入和回车。

在使用getline() 之前,您可以使用cin.ignore() 去掉那些多余的字符。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2021-03-19
      • 2015-05-06
      • 2017-02-13
      • 1970-01-01
      • 2012-01-04
      • 2022-01-05
      相关资源
      最近更新 更多