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