C++ Error Checking (Simple program)

In summary, the conversation is about a program that calculates the average and standard deviation of data entered by the user into a vector. The size of the vector is also determined by the user. The code includes a check for a positive integer input for the vector size, but the user can still enter "bad data" (e.g. the letter A) when inputting the actual data into the vector, causing the program to terminate and return 0 for everything. The solution suggested is to use an inner while loop with getline() to input the data as a string, perform checks and parse the string as a number to avoid interference from cin.
  • #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
}
[/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
  • #2
I edited your listing using the [_code=c_] tags but I lost your bolded code.

Could you repost that section?
 
  • #3
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.
 
  • #4
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 :)
 

Related to C++ Error Checking (Simple program)

1. What is C++ error checking?

C++ error checking is a process of detecting and handling errors in a C++ program. It helps to ensure that the program runs smoothly without unexpected crashes or errors.

2. Why is error checking important in C++?

Error checking is important in C++ because it helps to prevent unexpected crashes and errors in the program. It also makes the code more robust and easier to debug.

3. How does C++ handle errors?

C++ handles errors through the use of exceptions and error codes. Exceptions are used to handle runtime errors, while error codes are used to handle compile-time errors.

4. What are some common errors in C++ programs?

Some common errors in C++ programs include syntax errors, logical errors, and memory-related errors such as memory leaks and segmentation faults.

5. How can I improve error checking in my C++ program?

To improve error checking in your C++ program, you can use try-catch blocks to handle exceptions, use assertions to check for logical errors, and use proper memory management techniques to avoid memory-related errors.

Similar threads

  • Engineering and Comp Sci Homework Help
Replies
2
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
3
Views
852
  • Engineering and Comp Sci Homework Help
Replies
3
Views
996
  • Engineering and Comp Sci Homework Help
Replies
2
Views
1K
  • Engineering and Comp Sci Homework Help
Replies
19
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
24
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
8
Views
2K
  • Engineering and Comp Sci Homework Help
Replies
1
Views
9K
  • Engineering and Comp Sci Homework Help
Replies
6
Views
3K
  • Engineering and Comp Sci Homework Help
Replies
10
Views
2K
Back
Top