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

C++入门作业:如何忽略输入中间小数以读取4个int整数

解决方案

要解决输入中间包含小数的容错问题,核心是每次读取整数后,把输入流中剩余的非整数部分(比如小数的.和后续数字)全部忽略,确保下一次读取整数时输入流处于正确位置。结合你的作业要求(仅用一个int变量、无控制语句),修改后的代码如下:

代码实现(标准库规范写法)

#include <iostream>
#include <limits>

using namespace std;

int main() {
    int integer;

    cout << "Enter four integers: ";

    cin >> integer;
    cout << "You entered the numbers: " << integer;
    cin.ignore(numeric_limits<streamsize>::max(), ' ');

    cin >> integer;
    cout << " " << integer;
    cin.ignore(numeric_limits<streamsize>::max(), ' ');

    cin >> integer;
    cout << " " << integer;
    cin.ignore(numeric_limits<streamsize>::max(), ' ');

    cin >> integer;
    cout << " " << integer << "\n\n";
    cin.ignore(numeric_limits<streamsize>::max(), '\n');

    return 0;
}

简化版本(无需额外头文件)

如果作业不允许引入<limits>头文件,可用一个足够大的数值代替标准库的最大忽略范围,比如你原代码中的1000:

#include <iostream>

using namespace std;

int main() {
    int integer;

    cout << "Enter four integers: ";

    cin >> integer;
    cout << "You entered the numbers: " << integer;
    cin.ignore(1000, ' ');

    cin >> integer;
    cout << " " << integer;
    cin.ignore(1000, ' ');

    cin >> integer;
    cout << " " << integer;
    cin.ignore(1000, ' ');

    cin >> integer;
    cout << " " << integer << "\n\n";
    cin.ignore(1000, '\n');

    return 0;
}

原理说明

  • 当输入类似1 2.7 3abc 4时:
    1. 第一次cin >> integer读取1后,cin.ignore(...)会跳过从当前位置(.7的起始处)直到下一个空格的所有字符,彻底清除小数部分。
    2. 第二次读取2后,同样跳过剩余杂项,确保下一次读取能定位到3。
    3. 前三次读取后用空格作为终止符,保证跳过当前整数后的所有非有效内容;最后一次读取后用换行作为终止符,处理末尾的文本。
  • 这种写法完全符合作业要求:仅用一个int变量,未使用任何控制语句(如if、while),同时兼容小数、末尾文本的输入场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 00:34:49