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

如何实现C++中double变量仅通过cin接收合法数字输入?

问题解决:输入非法内容时的处理优化

你的代码在输入非数字内容时,cin会进入错误状态,导致后续输入操作全部失败,且未初始化的add_num会被默认设为0,因此会循环输出"0.00 added"。以下是针对性修复方案:

核心修改逻辑

修改addNumbers函数,添加输入有效性校验,同时处理cin的错误状态并清空输入缓冲区,避免非法内容干扰后续操作:

void addNumbers(vector<double> &vec) {
    double add_num {};
    cout << "Enter a number to add: ";
    // 校验输入是否成功解析为double类型
    if (cin >> add_num) {
        vec.push_back(add_num);
        cout << add_num << " added" << endl;
    } else {
        cout << "Invalid number" << endl;
        // 清除cin的错误状态标志
        cin.clear();
        // 清空输入缓冲区中剩余的非法字符,直到换行符
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }
}

补充说明

  • 当cin >> add_num失败时,cin会设置错误位,此时所有后续输入都会直接失败,必须用cin.clear()清除错误状态才能恢复正常输入
  • cin.ignore(...)会清空输入缓冲区里的非法内容(比如输入的字符串),避免这些内容被后续菜单选择的输入操作读取,导致菜单功能异常
  • 原代码提示文字为"Enter an integer to add",但实际使用double类型存储数值,建议改为"Enter a number to add"更准确

完整修复后的代码

#include <iostream>
#include <vector>
#include <iomanip>
#include <cctype>
#include <algorithm> // 单独包含min_element/max_element所需头文件,替代冗余的bits/stdc++.h
#include <limits>    // 用于numeric_limits

using namespace std;

char choice {};

char menu();
void print(vector<double>);
void mean(vector<double>);
void addNumbers(vector<double> &vec);
void smallest(vector<double>);
void largest(vector<double>);

char menu() {
    cout << "\nP - Print numbers" << endl;
    cout << "A - Add a number" << endl;
    cout << "M - Display mean of the numbers" << endl;
    cout << "S - Display the smallest number" << endl;
    cout << "L - Display the largest number" << endl;
    cout << "Q - Quit" << endl;
    cout << "\nEnter your choice: ";
    cin >> choice;
    choice = toupper(choice);
    return choice;
}

void print(vector<double> vec) {
    if (vec.size() != 0) {
        cout << "[ ";
        for (auto i : vec) {
            cout << i << " ";
        }
        cout << "]" << endl;
    } else {
        cout << "[] - the list is empty" << endl;
    }
}

void addNumbers(vector<double> &vec) {
    double add_num {};
    cout << "Enter a number to add: ";
    if (cin >> add_num) {
        vec.push_back(add_num);
        cout << add_num << " added" << endl;
    } else {
        cout << "Invalid number" << endl;
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }
}

void mean(vector<double> vec) {
    if (vec.size() != 0) {
        double result {};
        for (auto i : vec) {
            result += i;
        }
        cout << "The mean is " << result / vec.size() << endl;
    } else {
        cout << "Unable to calculate the mean - no data" << endl;
    }
}

void smallest(vector<double> vec) {
    if (vec.size() != 0) {
        cout << "The smallest number is " << *min_element(vec.begin(), vec.end()) << endl;
    } else {
        cout << "Unable to determine the smallest number - list is empty" << endl;
    }
}

void largest(vector<double> vec) {
    if (vec.size() != 0) {
        cout << "The largest number is " << *max_element(vec.begin(), vec.end()) << endl;
    } else {
        cout << "Unable to determine the largest number - list is empty" << endl;
    }
}

int main() {
    vector<double> vec {};
    bool done {true};
    cout << fixed << setprecision(2);

    do {
        menu();
        switch (choice) {
            case 'P':
                print(vec);
                break;
            case 'A':
                addNumbers(vec);
                break;
            case 'M':
                mean(vec);
                break;
            case 'S':
                smallest(vec);
                break;
            case 'L':
                largest(vec);
                break;
            case 'Q':
                cout << "Goodbye" << endl;
                done = false;
                break;
            default:
                cout << "Unknown selection, please try again" << endl;
        }
    } while (done == true);
    return 0;   
}

额外优化:移除了冗余的#include <bits/stdc++.h>,改为单独包含所需头文件,符合C++编码规范;同时在print函数中补充endl,避免输出后不换行影响菜单显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 14:45:57