C++如何使双精度变量只能用cin输入数字

ki1q1bka  于 2022-11-19  发布在  其他
关注(0)|答案(3)|浏览(204)
void addNumbers(vector<double> &vec) {
    double add_num {};
    cout << "Enter an integer to add: ";
    cin >> add_num;
    vec.push_back(add_num);
    cout << add_num << " added" << endl;
}

向量是空的,我只希望人们能够向其中添加数字,每当他们尝试其他任何东西时它都会说“无效数字”。
完整的代码如下,如果我在lol中输入了数字以外的内容,它就会一遍又一遍地循环说“0.00 added

#include <iostream>
#include <vector>
#include <bits/stdc++.h>
#include <iomanip>
#include <cctype>
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 << "]";
    }
    else {
        cout << "[] - the list is empty" << endl;
    }
}

void addNumbers(vector<double> &vec) {
    double add_num {};
    cout << "Enter an integer to add: ";
    cin >> add_num;
    vec.push_back(add_num);
    cout << add_num << " added" << endl;
}

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;   
}
j2cgzkjk

j2cgzkjk1#

你需要检查提取命令cin >> add_num的返回代码,通常,你需要检查任何IO操作后流的状态。
那么,会发生什么呢?如果您输入了任何无效的数据,例如“abc”,那么cin >> add_num当然将无法工作,并且流的状态(cin)将设置它的一个故障位。请紧急检查this
如果你不清除这个错误,那么这个错误就会一直存在。所有在cin上的后续操作都会失败。所以,你需要调用流的clear()函数。但是仅仅这样做是没有用的。在输入流中可能仍然有无效的字符。这些字符必须被消除。
您可以使用ignore函数来执行以下操作:

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

如果你想确保得到所需的值,那么你可以想出类似下面的东西:

#include <iostream>
#include <vector>
#include <limits>
using namespace std;

void addNumbers(vector<double> &vec) {
    double add_num {};
    
    bool isValidNumber{};
    while (not isValidNumber) {
        
        cout << "Enter an integer to add: ";
        if (cin >> add_num) {
            isValidNumber = true;
        }
        else {
            cin.clear();
            cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
        }
    }   
    
    vec.push_back(add_num);
    cout << add_num << " added" << endl;
}

int main() {
    std::vector<double> values{};
    addNumbers(values);
}
9rnv2umw

9rnv2umw2#

void addNumbers(vector<double>& vec) {
    double add_num{};
    string s;
    cout << "Enter an integer to add: ";
    cin >> s;
    try {
        add_num = stof(s);
    }catch (exception& e) {
        printf("error=%s\n", e.what());
        return;
    }
    vec.push_back(add_num);
    cout << add_num << " added" << endl;
}
fnvucqvd

fnvucqvd3#

void addNumbers(vector<double> &vec) {
    int add_num=0;
    std::cout << "Enter an integer to add: ";
    if( std::cin >> add_num ) {
        vec.push_back((double)add_num);
        std::cout << add_num << " added" << std::endl;
    } else {
        std::cout << "It's not a valid number." << std::endl;
        std::cin.clear(); // to clear error status
        std::cin.ignore(1000,'\n');  // to ignore characters in buffer entered.
        return;
    }
}

相关问题