Comp Sci C++ Error Checking (Simple program)

AI Thread Summary
The discussion focuses on improving error handling in a C++ program that calculates the average and standard deviation from user input. The user must enter a positive integer for the vector size, which is already implemented correctly. However, when entering data into the vector, the program crashes if non-numeric input is provided. A suggested solution involves using a string variable with `getline()` to read input, followed by checks to validate and parse the string as a number. This approach will prevent premature termination of the program due to invalid data entry.
AKJ1
Messages
43
Reaction score
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
}
[/B]
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:
Physics news on Phys.org
I edited your listing using the [_code=c_] tags but I lost your bolded code.

Could you repost that section?
 
I would adjust your for loop with an inner while loop where you input the data as a string via getline() and then do some checks and parse the string as a number.

In this way cin won't get in the way reject it prematurely.
 
jedishrfu said:
I would adjust your for loop with an inner while loop where you input the data as a string via getline() and then do some checks and parse the string as a number.

In this way cin won't get in the way reject it prematurely.

Hmm, how would I do this? Should I make a string variable and getline(cin,string variable) ? I am not as familiar with getline, so if what I said makes no sense then I apologize :)
 

Similar threads

Replies
2
Views
3K
Replies
3
Views
1K
Replies
3
Views
1K
Replies
6
Views
3K
Replies
2
Views
2K
Replies
8
Views
1K
Replies
1
Views
10K
Back
Top