- #1
AKJ1
- 43
- 0
Homework Statement
I am writing a program that will calculate the average and standard deviation given data by the user. The data is entered into a vector. The size of the vector is also determined by the user.
When the user enters the size of their vector, they need to enter a positive integer, if they don't the program will tell them to do so (If they enter the letter A, the program will prompt them to enter a positive integer). This part I have completed.
However, when they actually enter their data into the vector, if they enter the letter A or any other character besides a number, the program terminates and returns 0 for everything. How can I make it so that if they give the vector "bad data", my program can tell them it is not a number and have them re enter it.
I bolded the part of the code that gets the values from the user.
I am a complete novice when it comes to programming and am trying to self teach.
The Attempt at a Solution
Code:
#include <iostream>
#include <vector>
#include <cmath>
#include <exception>
#include <typeinfo>
#include <limits>
using namespace std;
float square(float x) //Returns square of a number
{
return x*x;
}float average(vector<float>& values) //Returns average values
{
float sum = 0;
for(int i = 0;i<values.size();++i)
{
sum+=values[i]; // Calculates the sum
}
return sum/values.size(); // Calculates the average
}float stddeviation(vector<float>& values) //Returns standard deviation
{
float std_sum = 0;
float mean = average(values);
for(int i = 0;i<values.size();++i)
{
std_sum += square(values[i]-mean);
}
return sqrt(std_sum/(values.size()-1));
}
// Main
int main(int argc, const char * argv[])
{
cout<< "Please enter the number of values: \n";
int num;
bool valid = false;
while ( !(cin >> num) || cin.peek() != '\n' || num < 0)
{
cout << "Enter a positive integer" << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
vector<float> values(num);//Intialize values to hold num values
cout<<"Please enter values, numbers only: \n";
for(int i = 0; i<num;++i) // Input values to vector
{
cin>>values[i];
}
cout<<"Average: "<<average(values)<<"\n";
cout<<"Standard Devation: "<<stddeviation(values)<<"\n";
return 0; //End
}
Edit-
This is the part of the code where I want the user to be prompted if they enter "bad data" into the vector
for(int i = 0; i<num;++i) // Input values to vector
{
cin>>values;
}
Last edited: