Home > Mobile >  C how to make it so a double variable can only have numbers entered in using cin
C how to make it so a double variable can only have numbers entered in using cin

Time:11-15

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

The vector is empty, and I only want people to be able to add numbers into it, and whenever they try anything else it says "Invalid number".

The full code is below, and currently it just loops over and over saying "0.00 added" if I put something other than a number in lol

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

CodePudding user response:

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

CodePudding user response:

You need to check the return code of your extraction command cin >> add_num. And in general, you need to check the state of a stream after any IO operation.

So, what could happen? If you enter any invalid data, like for example "abc", then cin >> add_num will of course not work, and the state of the stream (cin) will set one of its failure bits. Please urgently check this.

And the failure will stay, unless you clear it. All further activities on cin will fail. SO, you need to call the clear() function of the stream. But this alone will not help. There may still be invalid characters in the input stream. And those must be eliminated.

You may use the ignore function for that:

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

And if you want to make sure to get the needed values, then you could come up with something like the below:

#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);
}

CodePudding user response:

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;
    }
}
  •  Tags:  
  • c
  • Related