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;
}
3条答案
按热度按时间j2cgzkjk1#
你需要检查提取命令
cin >> add_num
的返回代码,通常,你需要检查任何IO操作后流的状态。那么,会发生什么呢?如果您输入了任何无效的数据,例如“abc”,那么
cin >> add_num
当然将无法工作,并且流的状态(cin)将设置它的一个故障位。请紧急检查this。如果你不清除这个错误,那么这个错误就会一直存在。所有在cin上的后续操作都会失败。所以,你需要调用流的
clear()
函数。但是仅仅这样做是没有用的。在输入流中可能仍然有无效的字符。这些字符必须被消除。您可以使用ignore函数来执行以下操作:
如果你想确保得到所需的值,那么你可以想出类似下面的东西:
9rnv2umw2#
fnvucqvd3#