.exe has stopped working - c++

I'm pretty new to programming, and this program runs, but when I am able to enter the batting record, the console is presented with a Windows error ".exe has stopped working...". This has never happened before, and as a new programmer, I think it's scary.
#include <iostream>
using namespace std;
//Prototype to keep console from closing.
class KeepRunning {
public:
~KeepRunning() {
system("pause");}};
//Define batting values
#define H 1
#define h 1
#define O 1
#define o 1
#define W 0
#define w 0
#define S 0
#define s 0
#define P 0
#define p 0
int main ()
{
KeepRunning kr;
int player; //Assign player number
double sum; //Assign variable for sum of H, h and O, o
double sumHits; //Assign variable for sum of only H and h
double average; //Assign variable for average of H and O
char size[100]; //Allows compiler to view user input as array
int b; //Assign variable for integer size
int letters = 0; //Assing value of 0 to allow compiler to count
cout << "\t\t\tBatting Average Calculator\t\t";
cout << "\n\nEnter the player's number: ";
cin >> player;
cout << "Enter the player's batting record: ";
cin >> size;
bool invalid = false;
while(!invalid)
{
invalid = true;
if ((size[b] == 'H') || (size[b] == 'h')
|| (size[b] == 'O') || (size[b] == 'o')
|| (size[b] == 'W') || (size[b] == 'w')
|| (size[b] == 'S') || (size[b] == 's')
|| (size[b] == 'P') || (size[b] == 'p'))
{
continue;
}
else {
cout << "\nAcceptable batting record codes are: 'H','O','W','S','P'.
Please try again.\n";
invalid = false;
}
}
//Summate H, h, O, o
sum = H + h + O + o;
//Summate
sumHits = H + h;
//Calculate batting average
average = sumHits/sum;
cout << "\nPlayer " << player << "'s batting record: " << size << endl;
cout << "Player " << player << "'s batting average: " << average << endl;
std::cout << "Press ENTER to continue...";
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
return 0;
}
Okay, so I've made a couple of changes thanks to yall. But, I've got new problems. First, when I run the program and write a valid input, i.e. "HOWHHHOOWHSPP", nothing happens. The console just stays open displaying the prompts and inputs. Second, when I write an invalid input, i.e. "HOWQQQTTSHH" or anything not including the specific set of letters, the console closes immediately rather than displaying my error message. How can I have the console not only stay open, but redirect the program to start over for any invalid input?
Here's the new code:
#include <iostream>
using namespace std;
//Prototype to keep console from closing.
class KeepRunning {
public:
~KeepRunning() {
cin.get();}};
//Define batting values
#define H 1
#define h 1
#define O 1
#define o 1
#define W 0
#define w 0
#define S 0
#define s 0
#define P 0
#define p 0
int main ()
{
KeepRunning kr;
int player; //Assign player number
double sum; //Assign variable for sum of H, h and O, o
double sumHits; //Assign variable for sum of only H and h
double average; //Assign variable for average of H and O
char size[100]; //Allows compiler to view user input as array
int b=0; //Assign variable for integer size
int letters = 0; //Assing value of 0 to allow compiler to count
cout << "\t\t\tBatting Average Calculator\t\t";
cout << "\n\nEnter the player's number: ";
cin >> player;
cout << "Enter the player's batting record: ";
cin >> size;
bool invalid = false;
while (!invalid && size[b] != '\0')
{
if (size[b] != 'H' && size[b] != 'h' &&
size[b] != 'O' && size[b] != 'o' &&
size[b] != 'W' && size[b] != 'w' &&
size[b] != 'S' && size[b] != 's' &&
size[b] != 'P' && size[b] != 'p')
{
invalid = true;
}
else {
invalid = false;
}
}
//Summate H, h, O, o
sum = H + h + O + o;
//Summate
sumHits = H + h;
//Calculate batting average
average = sumHits/sum;
cout << "\nPlayer " << player << "'s batting record: " << size << endl;
cout << "Player " << player << "'s batting average: " << average << endl;
return 0;
}

In the lines
cout << "Enter the player's batting record: ";
cin >> size;
I think you should take input to b, not size. In your code b is uninitialized, so it contains garbage value. When you use b as index for size, the index is invalid, which causes your program to crash.

It looks like the problem is that you're attempting to use the variable b as the index to the array before assigning a value to it. I think what you want is a loop to check all of the characters entered by the user, so something like this:
int b = 0;
while (!invalid && size[b] != '\0') {
//stuff in your existing loop
}
'\0' is automatically added to the end of the user input and indicates to the loop that all of the characters entered by the user have been read.
As a side note, it would be good to restructure your loop to check if the input you're checking is invalid and if it is, set invalid to true. There's no reason to use continue here. Something like this would be better:
if (size[b] != 'H' && size[b] != 'h' &&
size[b] != 'O' && size[b] != 'o' &&
....etc.) {
invalid = true;
}
The loop will end as soon as an invalid character is encountered.

Related

How to prevent C++ buffer overflow if the user enters two or more strings separated by white spaces?

I'm a student, and I am currently working on C++ Classes. I am making a program which is supposed to ask a user to input a float point number not greater that 99.99 as a price of fuel at a gas station. I have created code that saves the user input in to a char array, and created limits so that the user can't input more than 2 dots, for example (2..2). The maximum number of characters is 5 including one dot. Now, everything works fine except for if the user enters two sets of strings before hitting enter. I have a problem because the second string messes up with other cin statements in the loop.
The code will also take the finalized char array input, and than covert it to a float variable so that the further calculations can be computed easily.
I am working on a Windows system, and Visual Studio 2017 C++.
I have tried detecting the single white space in an if/else statement, but it seems that white space is not detected as a single char array member, like this ex. else if (str[count] == ' ') , and than asking to re enter the correct input without the white space. getline() function could not work on a char array, so I couldn't discard the characters entered after including and after the white space in this way. I have tried changing the char array to a string, but still if the user inputs two or more strings separated by white space, my program keeps reading it in to cin over again.
int main()
{
int count = 0;
int lenFlag = 0, mainFlag = 0;
float result = 0;
int len;
char str[6] = "00000";
//string str ="00000";
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
//This part will ask the user to set the price of fuel
//for the gas pump program. The programming project segment
//is from a book by Walter Savitch "Absolute C++".
while (mainFlag == 0)
{
cout << "Please enter the fuel price in dollars $";
cin >> str;
len = strlen(str);
cout << "strlen is = " << len << endl;
while (len <= 5 && mainFlag == 0)
{
count = 0, lenFlag = 0;
while (count < len && lenFlag == 0)
{
if (count == 0 && (str[count] < 48 || str[count] > 57))
{
cout << "The first input member must be a number."
"You must use a number between 0-9.\n"
"Try again: ";
cin >> str;
len = strlen(str);
lenFlag = 1;
}
else if (count > 0 && (str[count] < 48 || str[count] > 57)
&& str[count] != '.')
{
cout << "You must enter number between 0-9, or a decimal delimiter.\n"
"Try again, : ";
cin >> str;
len = strlen(str);
lenFlag = 1;
}
else if (count > 0 && (str[0] == '.' && str[1] == '.') || (str[0] == '.' && str[2] == '.') ||
(str[0] == '.' && str[3] == '.') || (str[0] == '.' && str[4] == '.') ||
(str[1] == '.' && str[2] == '.') || (str[1] == '.' && str[3] == '.') ||
(str[1] == '.' && str[4] == '.') || (str[2] == '.' && str[3] == '.') ||
(str[2] == '.' && str[4] == '.') || (str[3] == '.' && str[4] == '.'))
{
cout << "You have entered more than 1 decimal delimiter, try again: ";
cin >> str;
len = strlen(str);
lenFlag = 1;
}
else if (count > 1 && str[0] > 48 && str[0] < 58 && str[1]>47
&& str[1] < 58 && str[2]>47 && str[2] < 58)
{
cout << "Maximum number is 99.99, try again:\n";
cin >> str;
len = strlen(str);
lenFlag = 1;
}
else if (str[count] == ' ')
{
cout << "Typing whitspace is not an option!!" << endl;
cout << "Try again!!" << endl;
cin >> str;
len = strlen(str);
lenFlag = 1;
}
else if (count == len - 1 && lenFlag == 0)
{
//cout << "Main flag switches to 1!!" << endl;
mainFlag = 1;
}
count++;
}
} //while(lenCopy <= 5) loop end
if (len > 5)
{
cout << "Either non-numbers were entered, or a negative
number, or an incorrect " << endl;
cout << "number size. Enter a maximum size of 5
including a .dot for decimal number" << endl;
cout << "Maximum number is 99.99." << endl;
mainFlag = 0;
}
}//mainflag loop ends
int dotpos = 0;
for (int n = 0; n < len; n++)
{
if (str[n] == '.')
{
//dotpos = n + 1;
dotpos = len - n - 1;
cout << "dotpos = " << dotpos << endl;
}
else
{
result = result * 10 + (str[n] - '0');
//Line above is a float and character mix as a math equation.
cout << "result " << n << " = " << result << endl;
}
}
if (dotpos > 0)
result = result / (power(10, dotpos));
cout << "You have set the cost at $" << result << " per gallon." << endl;
system("pause");
return 0;
}
Occasional stack around str variable has been corrupted, and that happens when I heavily try to mess with the user input just to check if the program can crash. That's why I need to know how to clear the input after the white space. I solved the stack corruption problem by changing the char array to string, but still not the excess characters that potential users might throw down at the program.
If you must use character arrays, I highly recommend restricting the amount of characters read from the console.
The std::istream::getline() is well suited for this:
const unsigned int LIMIT = 10;
char number_as_text[LIMIT];
std::cout << "Enter a floating point number, less than 10 characters: ";
std::cin.getline(number_as_text, LIMIT);
You can then use a function like strtod to convert the string to floating point variable.
I have found one good way to solve a problem of the string buffer overflow. It uses
cin>>ws; followed by getline() function. The two need to be used in conjunction, and
than the read will be only the first string of characters and everything after the whitespace will be trashed.
cout << "Do you want to set cost in gallons or liters? "
"\nPress G for gallons or L for liters: ";
cin >> ws;
getline(cin, chooseSetCost);
while (chooseSetCost != "G" && chooseSetCost != "g" && chooseSetCost != "L" && chooseSetCost != "l")
{
cout << "Incorrect input. Try again: ";
cin >> ws;
getline(cin, chooseSetCost);
cout << "choose cost is = " << chooseSetCost << endl;
}

Looping assignment in C++

My assignment is utilizing loops. The program should accept input for the sales of 3 employees (Mary, Tom, and Chris). The flow should be as follows:
Initial? > number of sales to enter > enter sale amounts > display commission for sale at 17% > adds commission and sales to the respective variables >> continue until 'z' is input for inputSalesPerson >> display information
So I am trying to figure out why my return value for the tempComm variable isn't returning the correct value. If i was to enter 't' for variable inputSalesPerson it puts me into the switch case 't' no problem. Input number of sales and that works. But when I get to entering the salesAmount and then displaying commission it will not calculate correctly.
Also if I enter 'z' or 'Z' as the inputSalesPerson it will not end the program. I have a lot to go on this.
#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
int salesT = 0, salesC = 0, salesM = 0;
double amountT = 0, amountC = 0, amountM = 0;
double commT = 0, commC = 0, commM = 0;
double commRate = (17/100);
int num_sales;
double salesAmount, totalSales, tempComm;
char inputSalesPerson;
do
{
cout << "Enter the sales person's initial (\"Z\" to quit): ";
cin >> inputSalesPerson;
while(inputSalesPerson != 't' && inputSalesPerson != 'T' && inputSalesPerson != 'm' && inputSalesPerson != 'M' && inputSalesPerson != 'c' && inputSalesPerson != 'C' && inputSalesPerson != 'z' && inputSalesPerson != 'Z')
{
cin.get();
system("cls");
cout << "Invalid input for employee. Please Input (T)om, (C)hris, (M)ary, or (Z) to End : ";
cin >> inputSalesPerson;
}
switch(inputSalesPerson)
{
case 't' :
case 'T' :
system("cls");
cout << "Enter the number of sales : ";
cin >> num_sales;
while(num_sales < 1 || num_sales > 5)
{
system("cls");
cout << "Invalid number of sales. Please enter a value between 1 and 5 : ";
cin >> num_sales;
}
salesT += num_sales;
for(int i = 0; i<num_sales; i++)
{
cin.get();
system("cls");
cout << "Enter the sale amount : ";
cin >> salesAmount;
while(salesAmount < 0)
{
cin.get();
system("cls");
cout << "Invalid sale amount. Please enter a positive amount : ";
cin >> salesAmount;
}
tempComm = salesAmount + (salesAmount * commRate);
cout << fixed << setprecision(2) << "Commission earned by tom on this sale is : " << tempComm << endl;
cin.get();
amountT += salesAmount + tempComm;
commT += tempComm;
totalSales += amountT;
}
break;
}
}while(inputSalesPerson != 'z' || 'Z');
return 0;
}
****EDIT****
Thank you for the information on single-step debugging. Thanks to that comment I was able to learn about using the debugging tool more in depth and that helped me get everything working a bit better.
I've commented your code at the areas that need fixing. Also, there's a problem with using cin.get() all over the place. I assume that you do this to discard the return character after each input. But if the standard input (cin) is empty when you call cin.get() it will block the program until something is input. This is what happens when you enter more than one num_sales:
for (int i = 0; i<num_sales; i++)
{
cin.get();
It handles the first fine, but on the second loop you get:
Enter the sale amount : 20
Commission earned by tom on this sale is : 23.40
// cin.get() blocks here, with no user instructions to enter the next sale amount
I've commented out all the cin.get(). It will still work the same because the cin operator >> discards whitespaces and newlines, so even if there is a \n newline character still in the buffer, the next time you do something like cin >> num_sales it will discard the newline anyway.
#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
int salesT = 0, salesC = 0, salesM = 0;
double amountT = 0, amountC = 0, amountM = 0;
double commT = 0, commC = 0, commM = 0;
double commRate = (17 / 100.0); // Int divided by int will round to an int.
// commRate is 0.0. Divide by double instead (17 / 100.0)
int num_sales;
double salesAmount, totalSales = 0, tempComm; // totalSales needs to be initialised to
// zero, otherwise it holds a garbage value.
char inputSalesPerson;
do
{
cout << "Enter the sales person's initial (\"Z\" to quit): ";
cin >> inputSalesPerson;
while (inputSalesPerson != 't' && inputSalesPerson != 'T' && inputSalesPerson != 'm' && inputSalesPerson != 'M' && inputSalesPerson != 'c' && inputSalesPerson != 'C' && inputSalesPerson != 'z' && inputSalesPerson != 'Z')
{
//cin.get();
system("cls");
cout << "Invalid input for employee. Please Input (T)om, (C)hris, (M)ary, or (Z) to End : ";
cin >> inputSalesPerson;
}
switch (inputSalesPerson)
{
case 't':
case 'T':
system("cls");
cout << "Enter the number of sales : ";
cin >> num_sales;
while (num_sales < 1 || num_sales > 5)
{
system("cls");
cout << "Invalid number of sales. Please enter a value between 1 and 5 : ";
cin >> num_sales;
}
salesT += num_sales;
for (int i = 0; i<num_sales; i++)
{
//cin.get();
//system("cls");
cout << "Enter the amount for sale number " << i+1 << ": ";
cin >> salesAmount;
system("cls"); // I would put the clear here,
// Otherwise the user can't see the commission made by Tom
while (salesAmount < 0)
{
//cin.get();
system("cls");
cout << "Invalid sale amount. Please enter a positive amount : ";
cin >> salesAmount;
}
tempComm = salesAmount + (salesAmount * commRate);
cout << fixed << setprecision(2) << "Commission earned by tom on this sale is : " << tempComm << endl;
//cin.get();
amountT += salesAmount + tempComm;
commT += tempComm;
totalSales += amountT; // I think you mean to add salesAmount maybe?
}
break;
}
} //while (inputSalesPerson != 'z' || 'Z');
// Even if { this ^^^^} is false, ^^^ this is always
// 'Z' char will convert to bool, any non-zero value is true.
while (inputSalesPerson != 'z' && inputSalesPerson != 'Z');
return 0;
}

Storing multiple user input into an array

I am currently working on a program for a project, that asks for the user to enter the specific sport they want to play and their age for reservations at a recreation area. I am confused on how to store their sport and age into an array so that it can be displayed later in the program, if they select to view all reservations made by one or more users. If anyone could help me with figuring out how to store a single or multiple user input into an array so that it can be displayed later in the program that would be great!
#include <iostream>
#include <string>
using namespace std;
int main()
{
char t; // Type of sport selected
char g, G; // Gliding
char h, H; // Hang-gliding
char f, F; //Flying
int a; // Age of patron
double x; // Rates
int s; // Selection from menu
int i; // Arrays variable
int num;
char sport[100]; // Array for all sports of patrons
int age[100]; // Array for all ages of patrons
cout << "Please pick from the following menu" << endl;
cout << "1. Add a new reservation" << endl;
cout << "2. Print all reservations" << endl;
cout << "3. Print all reservations for a given sport" << endl;
cout << "4. Quit" << endl;
cin >> s;
for (i = 0; i < num; ++i)
if (s == 1) {
cout << "Please enter f/F for flying, g/G for gliding and h/H for hang-gliding" << endl;
cin >> t;
getline (cin, sport[i]);
cout << "Please enter the age of patron, minimum age is 16" << endl;
cin >> a;
if ((t == 'f' || t == 'F') && (a <= 25)) {
x = 68.95;
}
else if ((t == 'g' || t == 'G') && (a <= 25)) {
x = 73.95;
}
else if ((t == 'h' || t == 'H') && (a <= 25)) {
x = 99.95;
}
else if ((t == 'f' || t == 'F') && (a > 25)) {
x = 55.95;
}
else if ((t == 'g' || t == 'G') && (a > 25)) {
x = 65.95;
}
else if ((t == 'h' || t == 'H') && (a > 25)) {
x = 92.95;
}
cout << "The insurance rate is $ " << x << endl;
}
else if (s == 2) {
cout << "A patron aged " << a << " reserved a session of " << t << endl;
}
else if (s == 3) {
}
else if (s == 4);
return 0;
You should make a class Patron that contains the multiple informations, then make an array of type Patron instead of multiple arrays:
class Patron
{
//data for each patron...
};
in main:
Patron patrons[...];
You could also use dynamic containers, like vector instead of an array.
std::vector<Patron> patrons;

Add a loop that allows me to display error statement and return to a certain place in the code

I'm trying to write a code that calculates batting average. I've got a couple of kinks right now. First, I'm trying to add an error message which would end progress and redirect the user to a previous point if they enter a foul string. I'm wanting this to happen where the program states "'Acceptable batting record codes are....'". How can I make the program request the players batting record again, and continue the code from there rather than continuing?
#include <iostream>
using namespace std;
//Prototype to keep console from closing.
class KeepRunning {
public:
~KeepRunning() {
system("pause");}};
//Define batting values
#define H 1
#define h 1
#define O 1
#define o 1
#define W 0
#define w 0
#define S 0
#define s 0
#define P 0
#define p 0
int main ()
{
KeepRunning kr;
int player; //Assign player number
double sum; //Assign variable for sum of H, h and O, o
double sumHits; //Assign variable for sum of only H and h
double average; //Assign variable for average of H and O
char size[100]; //Allows compiler to view user input as array
int b; //Assign variable for integer size
int letters = 0; //Assing value of 0 to allow compiler to count
cout << "\t\t\tBatting Average Calculator\t\t";
cout << "\n\nEnter the player's number: ";
cin >> player;
cout << "Enter the player's batting record: ";
cin >> size;
{b = 0;
while (size[b] != 0)
if (( size[b] = 'h','o','w','s','p') || (size[b] = 'H','O','W','S','P'))
{ letters++; b++; }
else ( size[b] != 'h','o','w','s','p') || (size[b] != 'H','O','W','S','P');
{cout << "\nAcceptable batting record codes are: 'H','O','W','S','P'. Please try again.\n";}}
//Summate H, h, O, o
sum = letters;
//Summate
sumHits = H + h;
//Calculate batting average
average = sumHits/sum;
cout << "\nPlayer " << player << "'s batting record: " << size << endl;
cout << "Player " << player << "'s batting average: " << average << endl;
std::cout << "Press ENTER to continue...";
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
return 0;
}
This:
if (( size[b] = 'h','o','w','s','p') || (size[b] = 'H','O','W','S','P'))
{ letters++; b++; }
else ( size[b] != 'h','o','w','s','p') || (size[b] != 'H','O','W','S','P');
{cout << "\nAcceptable batting record codes are: 'H','O','W','S','P'. Please try again.\n";}}
This is not C++. You cannot compare size[b] with a group of elements like that, besides = is an assignment operator, as when you are assigning a value to the variable. If you were to compare both, you should use ==.
In else you don't include new conditions. It works as if [condition] do { this }, or else do { something else }. If you ever need to be further specific in conditions use else if.
There are many ways to achieve what you seem to want here. You can compare size[b] with each element you want, for instance:
if ((size[b] == 'H') || (size[b] == 'h')
|| (size[b] == 'O') || (size[b] == 'o')
|| (size[b] == 'W') || (size[b] == 'w')
|| (size[b] == 'S') || (size[b] == 's')
|| (size[b] == 'P') || (size[b] == 'p')) {
letters++; b++;
} else {
cout << "\nAcceptable batting record codes are: 'H','O','W','S','P'. Please try again.\n";
}
Or with switch for clearer looks:
switch (std::tolower(size[b]))
{
case 'h':
case 'o':
case 'w':
case 's':
case 'p':
letters++;
b++;
break;
default:
cout << "\nAcceptable batting record codes are: 'H','O','W','S','P'. Please try again.\n";
}
Or even with a std::set of valid elements:
// at some part of program beginning
const char _dictionary[] = { 'h', 'o', 'w', 's', 'p' };
const std::set<char> dictionary(_dictionary, _dictionary + 5);
if (dictionary.find(std::tolower(size[b])) != dictionary.end()) {
letters++;
b++;
}
else {
cout << "\nAcceptable batting record codes are: 'H','O','W','S','P'. Please try again.\n";
}

Console closing prematurely. EDIT: Sum and Average not computing correctly

This code works well as long as I write an invalid input. The error message prints, and you just have to close the console and start over. But, can I have the program start again from the beginning with the console open? Also, the big failure, and prime question, is that when a valid input is entered, the console just closes. I have no idea why, and I'm new to C++, so please bear with me. :)
EDIT: Now that #merlin2011 was so kind as to point out my super simple mistake, the program is doing much better! Thanks a million! But, the new problem on the street is that my calculations aren't working correctly. I printed my sum to see if it's correct, and I think because I have int letters = 0;, it counts the sum as 0. I think I need to change this to a reference integer? So int& letters =0;, but how can I have it store it's new value later??
#include <iostream>
using namespace std;
//Prototype to keep console from closing.
class KeepRunning {
public:
~KeepRunning() {
cin.get();}};
//Define batting values
#define H 1
#define h 1
#define O 1
#define o 1
#define W 0
#define w 0
#define S 0
#define s 0
#define P 0
#define p 0
int main ()
{
KeepRunning kr;
int player; //Assign player number
double sum; //Assign variable for sum of H, h and O, o
double sumHits; //Assign variable for sum of only H and h
double average; //Assign variable for average of H and O
char size[100]; //Allows compiler to view user input as array
int b=0; //Assign variable for integer size
int letters = 0; //Assing value of 0 to allow compiler to count
cout << "\t\t\tBatting Average Calculator\t\t";
do
{
cout << "\n\nEnter the player's number: ";
cin >> player;
cout << "Enter the player's batting record: ";
cin >> size;
if (size[b] != 'H' && size[b] != 'h' &&
size[b] != 'O' && size[b] != 'o' &&
size[b] != 'W' && size[b] != 'w' &&
size[b] != 'S' && size[b] != 's' &&
size[b] != 'P' && size[b] != 'p' || cin.fail())
{
cout << "\nAcceptable batting record codes are: 'H','O','W','S','P'.Please try again.\n";
cin.clear();
cin.ignore();
}
} while (size[b] != 'H' && size[b] != 'h' &&
size[b] != 'O' && size[b] != 'o' &&
size[b] != 'W' && size[b] != 'w' &&
size[b] != 'S' && size[b] != 's' &&
size[b] != 'P' && size[b] != 'p' || cin.fail());
return 0;
//Summate H, h, O, o
sum = letters;
//Summate
sumHits = H + h;
//Calculate batting average
average = sumHits/sum;
cout << "\nPlayer " << player << "'s batting record: " << size << endl;
cout << "Player " << player << "'s batting average: " << average << endl;
std::cout << "Press ENTER to continue...";
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
}
Where to start...
As #merlin2011 said, anything below the line `return 0;' will not execute.
User input is not really used (except for the validation). I have no idea of what you are trying to do, but I'd say that size contents should have some influence in sumHits.
letters is not increased anywhere. Its definition is fine (don't touch it!)... just needs to increase it for each item in the average.
b is not increased anywhere. I could guess that your input is a string of letters, each of them meaning something... so you're probably missing a loop on b that goes over the string of letters, increasing letters and adding values to sumHits according to the different letters entered by the user.
btw, using #define for constants is considered bad practice in C++...
modified code:
#include <iostream>
#include <limits> // added because of the numeric limits at the end
#include <cstring> // added because of strlen
using namespace std;
//Prototype to keep console from closing.
//This is probably not needed anymore
class KeepRunning {
public:
~KeepRunning() {
cin.get();}};
int main ()
{
KeepRunning kr; // not sure if this is needed
int player; //Assign player number
double sumHits; //Assign variable for sum of only H and h
double average; //Assign variable for average of H and O
char size[100]; //Allows compiler to view user input as array
int b=0; //Assign variable for integer size
int letters = 0; //Assing value of 0 to allow compiler to count
// probably the above variables can be moved inside the loop.
cout << "\t\t\tBatting Average Calculator\t\t";
do
{
cout << "\n\nEnter the player's number: ";
cin >> player;
cout << "Enter the player's batting record: ";
cin >> size;
// Now size should probably be a std::string...
// Now we have an input, loop through it
// initialize variables
letters = 0;
sumHits = 0.0;
for(b=0;b<strlen(size);b++) {
// Now check each letter
switch(size[b]) {
case 'H': // fallthrough
case 'h':
sumHits+=1;
letters++;
break;
case 'O': // fallthrough
case 'o':
letters++;
break;
case 'S': // fallthrough
case 's': // fallthrough
case 'P': // fallthrough
case 'p': // fallthrough
// not sure what these are... so just skip
break;
default:
// syntax error
cout << "\nAcceptable batting record codes are: 'H','O','W','S','P'.Please try again.\n";
cin.clear();
cin.ignore();
letters=0; // reset the count so that we don't process the average
}
}
if(letters==0) {
// we didn't get a valid input, start the loop again
continue;
}
//Calculate batting average
average = sumHits/letters;
cout << "\nPlayer " << player << "'s batting record: " << size << endl;
cout << "Player " << player << "'s batting average: " << average << endl;
std::cout << "Press ENTER to continue...";
std::cin.ignore( std::numeric_limits<std::streamsize>::max(), '\n' );
}
while(!cin.fail()); // repeat until the standard input ends.
}