【问题标题】:Program is skipping getline () / C++ [duplicate]程序正在跳过getline()/ C++ [重复]
【发布时间】:2016-12-17 12:13:18
【问题描述】:

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

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

程序只读取选择并结束整个过程:/,请帮助:D

【问题讨论】:

    标签: c++ string std cin getline


    【解决方案1】:

    cin&gt;&gt;Choice; 将尾随换行符留在输入缓冲区中。而getline(cin,title); 则读取一个空行。

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

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

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

    【讨论】:

    • 非常感谢:D,它成功了
    【解决方案2】:

    这句话之后

        cin>>Choice;
    

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

    所以下一条语句用getline

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

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

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

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

    清除缓冲区。

    【讨论】:

      猜你喜欢
      • 2021-11-26
      • 2017-02-13
      • 1970-01-01
      • 2021-11-24
      • 2011-05-03
      • 1970-01-01
      • 1970-01-01
      • 2016-02-05
      相关资源
      最近更新 更多