C++ Error Checking (Simple program)

  • Context: Comp Sci 
  • Thread starter Thread starter AKJ1
  • Start date Start date
  • Tags Tags
    C++ Error Program
Click For Summary

Discussion Overview

The discussion revolves around error checking in a C++ program designed to calculate the average and standard deviation of user-provided data. Participants are exploring how to handle invalid input when users enter non-numeric values into a vector.

Discussion Character

  • Homework-related
  • Technical explanation
  • Exploratory

Main Points Raised

  • The original poster (OP) describes a problem where the program terminates if the user inputs non-numeric characters when entering data into a vector.
  • Some participants suggest implementing an inner while loop to repeatedly prompt the user for input until valid data is entered.
  • One participant proposes using the getline() function to read input as a string, allowing for more flexible error checking before parsing the string into a number.
  • Another participant expresses uncertainty about how to implement the getline() approach and seeks clarification on its usage.

Areas of Agreement / Disagreement

There is no consensus on the best approach to handle invalid input, as participants are proposing different methods and seeking clarification on implementation details.

Contextual Notes

Participants have not reached a resolution on the specific implementation of error checking, and there are varying levels of familiarity with C++ functions such as getline().

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[])
{

    count<< "Please enter the number of values: \n";

    int num;

    bool valid = false;

    while ( !(cin >> num) || cin.peek() != '\n' || num < 0)
    {  
        count << "Enter a positive integer" << endl;
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
    }

    vector<float> values(num);//Intialize values to hold num values
    count<<"Please enter values, numbers only: \n";
    for(int i = 0; i<num;++i)  // Input values to vector
    {
        cin>>values[i];
    } 

    count<<"Average: "<<average(values)<<"\n";
    count<<"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 ·
Replies
2
Views
3K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 19 ·
Replies
19
Views
3K
  • · Replies 3 ·
Replies
3
Views
1K
  • · Replies 1 ·
Replies
1
Views
11K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 10 ·
Replies
10
Views
3K
  • · Replies 12 ·
Replies
12
Views
2K
  • · Replies 6 ·
Replies
6
Views
3K