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

