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

C++程序如何同时支持按回车键用默认值和用户自定义输入?

问题根源
  • cin.get()只会读取输入流中的单个字符:当你手动输入数值后按下回车,输入的数字后残留的\n会留在输入缓冲区,下一次调用cin.get()时会直接读取到这个残留换行,触发默认值逻辑,跳过用户输入环节。
  • 当cin.get()读取到的不是换行时,你已经把输入的第一个数字字符读走了,直接调用cin >> cookies会丢失第一个字符,导致读取的数值错误。
  • 原代码中计算剩余饼干、剩余盒子时硬编码了24、75,没有使用用户自定义的cookies、boxes变量,即使输入成功计算结果也会出错。
修复方案
  1. 若cin.get()读取到的不是换行符,先调用cin.unget()把读取到的第一个字符塞回输入流,再读取整数值。
  2. 每次输入处理完成后,调用cin.ignore(numeric_limits<streamsize>::max(), '\n')清空当前输入行剩下的所有内容,消除残留换行对后续输入的影响,需要引入<limits>头文件使用numeric_limits。
  3. 修改剩余量计算逻辑,使用用户设置的cookies、boxes变量而非硬编码数值。
修改后完整代码
#include <iostream>
#include <string>
#include <limits> // 新增头文件用于清空输入缓冲区

using namespace std;

int main()
{
    int cookies, boxes, cookieTotal, boxTotal, containerTotal, cookiesLeft, boxesLeft;

    cout << "Press Enter to use the default setting of 24 or input the number of cookies per box: ";
    if (cin.get() == '\n') {
        cookies = 24;
        cout << "24" << endl;
    }
    else {
        cin.unget(); // 把读走的第一个字符塞回输入流
        cin >> cookies;
        // 清空当前行残留的所有内容(包括换行)
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }
    
    cout << "Press Enter to use the default setting of 75 or input the number of box per container: ";
    if (cin.get() == '\n') {
        boxes = 75;
        cout << "75" << endl;
    }
    else {
        cin.unget();
        cin >> boxes;
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }

    cout << "Input the total about of cookies: ";
    cin >> cookieTotal;
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    // 修正硬编码问题
    boxTotal = cookieTotal / cookies;
    containerTotal = boxTotal / boxes;
    cookiesLeft = cookieTotal - (boxTotal * cookies);
    boxesLeft = boxTotal - (containerTotal * boxes);

    cout << "The total number of boxes: " << boxTotal << endl; 
    cout << "The total number of containers: " << containerTotal << endl;
    cout << "Leftover cookies: " << cookiesLeft << endl;
    cout << "Leftover boxes: " << boxesLeft << endl;

    char q;
    cout << "\nPress any key to Exit.";
    cin.get(q);

    return 0;
}

内容的提问来源于stack exchange,提问作者Yazy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 13:39:02