You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中std::getline()第二次调用无法正常生效问题求助

问题原因

cin >> 读取int、float等数值类型时,只会提取符合数值格式的字符,不会处理输入结束后按下回车产生的换行符\n,该字符会残留在输入缓冲区中。后续调用std::getline()时,默认以换行符作为行结束标记,会直接读取到这个残留的换行符,返回空字符串,看起来就像第二次getline没有生效,没有等待用户输入。

解决方案

有两种常用修复方式:

  • 方案1:每次使用cin >>读取数值后,主动丢弃缓冲区残留的换行符
    修改后完整代码如下:
    #include <iostream>
    #include <string>
    using namespace std;
    
    int main() {
        string bufName; //存储姓名
        int age;  //年龄为整型
        float temperature; //温度为浮点型
        string bufCity; //城市名可能包含空格,用getline读取
      
        cout << "Enter your Name please: " << endl;
        getline(cin, bufName);
        cout << "you Entered: " << bufName << endl;
      
        cout << "Enter your Age: " << endl;
        cin >> age ;
        cin.ignore(); //丢弃残留的换行符
        cout << "you Entered: " << age << endl;
      
        cout << "Enter the Temperature at your city please: " << endl;
        cin >> temperature ;
        cin.ignore(); //丢弃残留的换行符
        cout << "you entered: " << temperature << endl;
      
        cout << "Enter your city name please: " << endl;
        getline(cin, bufCity);
        cout << "you Entered: " << bufCity << endl;
        return 0;
    }
    
  • 方案2:所有输入统一使用std::getline()读取整行,再将字符串转换为对应数值类型,彻底避免缓冲区残留字符的问题,输入健壮性更高。

内容的提问来源于stack exchange,提问作者Ali A.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 12:00:02