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

11

我有这个简单的 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)"时,程序只是打印出"输入repo命令:",然后跳过了"getline(cin, rp.command)"这一行,导致用户没有时间回答。可能的问题是什么?
当执行到 "getline(cin, rp.command)" 时,程序会等待用户输入命令并按下回车键。如果该行被跳过,可能是由于之前的输入操作已经留下换行符,使得 getline() 函数读取到了一个空行。解决方法可以在输入操作前使用 cin.ignore() 来清除之前留下的换行符。

1
你的结构体长什么样? - user657267
4
上述代码不应该崩溃,你的问题可能出在其他地方,请发表一个最小可编译示例以展示崩溃情况。 - user657267
它是否会崩溃或rp.command保持为空? - ST3
你的堆在进入addToDatabase之前可能已经损坏了。你是否混合使用Visual Studio的不同版本或在调试应用程序中使用Release dll?请记住,在应用程序中使用与Visual Studio不同版本编译的dll通常是不安全的,这会创建超过1个独立的堆。 - drescherjm
我认为你应该使用 #include <iostream> 并在开头清除缓冲区。 - MarmiK
显示剩余9条评论
2个回答

16

在这里已经回答了重复的问题

基本上,当用户按下Enter键时,cin>>不会从缓冲区中删除换行符。 getline() 将此错误地视为用户输入加上Enter。

您可以在使用 getline() 之前使用 cin.ignore() 来摆脱这些额外的字符。


0

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

在使用getline()之前,您应该清空cin缓冲区


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接