程序正在跳过 getline() / C++

Program is skipping getline () / C++

每当我尝试 运行 此代码时:

string title;
        int Choice;
        cout<<"1. Insert new term ";
        cin>>Choice;
        if (Choice==1)
        {
            getline(cin,title);
        }

程序只读了Choice就结束了整个过程:/,求助:D

cin>>Choice; 在输入缓冲区中留下尾随的换行符。 getline(cin,title); 因此读取一个空行。

一般来说,最好不要将格式化输入与来自同一流的 getline 混在一起。

一个快速简单的解决方法是使用 std::basic_istream::ignore 从流中删除尾随的换行符,如下所示:

cin.ignore(2, '\n');

这条语句之后

    cin>>Choice;

输入缓冲区将包含按回车键留下的换行符。

所以下一条语句用 getline

    if (Choice==1)
    {
        getline(cin,title);

读取空字符串,直到遇到换行符。

在此语句之前插入以下调用

    #include <limits>

    //...


    {
        getline(cin,title);
        std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );

清除缓冲区。