My code is stuck in an infinite loop in C++ - visual-c++

I am trying to use a while loop to calculate the average of 3 inputted grades, but I can not enter the next grade as the loops keep on going without giving me the chance to enter the next grade.
#include<iostream>
using namespace std;
int main()
{
int grade = 0;
int count = 0;
int total = 0;
cout << "Enter grade: ";
cin >> grade;
while (grade != -1)
{
total = total + grade;
count = count + 1;
cout << "Enter next grade: ";
cin >> grade;
}
int(average) = total / 3;
cout << "Average: " << int(average) << endl;
system("pause");
}

I tested your code with integer and it works fine.
If you only take int as input, the best is to put something to check the input type. Use cin.fail() to check if user input anything other than int.
for example:
while(cin.fail()) {
cout << "Error" << endl;
cin.clear();
cin.ignore(256,'\n');
cout << "Please enter grade:"
std::cin >> grade;
}
which I refer from https://www.codegrepper.com/code-examples/cpp/how+to+check+type+of+input+cin+c%2B%2B
and here as well Checking cin input stream produces an integer

Related

Why VS 2015 is giving me the exception at the end of the code below?

I am somewhat new to c++, our class only went over debugging briefly. This is probably my 10th do over, I have been over it a week, have done plenty of research over the web and I just don't understand debugging enough to figure out how to fix my code. The program is supposed to real a file like this:
TTFTFTTTFTFTFFTTFTTF
ABC54102 T FTFTFTTTFTTFTTF TF
DEF56278 TTFTFTTTFTFTFFTTFTTF
ABC42366 TTFTFTTTFTFTFFTTF
ABC42586 TTTTFTTT TFTFFFTF
When it reads the file it's supposed to output the student ids, what they answered on each question and the grade for each student. My problem is, I don't know much about debugging and VS keeps throwing an exception at the end of the code I provided. I am just learning how to use dynamic arrays so I know it has something to do with my use of them because I had the program working fine in my other c++ class but I had to change it around to use dynamic arrays for this project.
What's wrong with my program? I have researched the web and reread the chapters in the book over and over and I cannot figure it out.
#include <iostream>
#include <string>
#include <fstream>
#include <stdlib.h>
#include <cstddef>
using namespace std;
// function prototypes
void readFile(ifstream& inFile);
char assignGrade(int score, int numQues);
int main()
{
int numQues = 20;
int numStud = 0;
string *studentIDs;
studentIDs = new string[numStud];
char *correctAnswers;
correctAnswers = new char[numStud];
char *studentAnswers;
studentAnswers = new char[numQues];
ifstream inFile;
cout << "\nRedo Programming Exercise Six of Chapter Eight\nUsing Dynamic Arrays..." << endl;
cout << "\nPlease Enter the Number of Students: ";
cin >> numStud;
cout << endl;
readFile(inFile);
inFile.getline(correctAnswers, '/n'); // read the correct answers first
for (int i = 0; i < numStud; i++) // loop students
{
inFile >> studentIDs[i]; // get the student ID
inFile.get(); // discard the space between the student ID and the answer
for (int j = 0; j < numQues; j++) // loop questions
{
studentAnswers[j] = inFile.get(); // get the student's answers
}// end for
cout << "Student ID: " << studentIDs[i] << endl; // output student id
int score = 0; // declare and initialize score to zero
cout << "Answers: "; // display "Answers: "
for (int j = 0; j < numQues; j++) // loop each question
{
cout << studentAnswers[j]; // output student's answers
if (studentAnswers[j] == correctAnswers[j]) // if student answer equals correct answer
score += 2; // correct answer
else if (studentAnswers[j] != correctAnswers[j] && studentAnswers[j] != ' ')
score -= 1; // incorrect answer but not a blank
else if (studentAnswers[j] == ' ')
score = 0;
delete[] studentAnswers;
}// end for
if (score < 0)
score = 0; // don't allow for negative scores
cout << endl; // new line, housekeeping
char grade = assignGrade(score, numQues); // call assignGrade function
cout << "Grade: " << grade << "\n" << endl; // display grade
}// end for
delete[] studentIDs;
system("pause");
return(0);
}
void readFile(ifstream& inFile)
{
inFile.open("Ch12_Ex2Data.txt"); // use inFile to open Ch8_Ex6Data.txt
if (!inFile) // if the file can't be opened or it is corrupt
{
cout << "There was an error opening the input file...\nPlease check file and try again!\n" << endl; // display error message
system("pause");
exit(1); // exit the program
}
} // end readFile function
char assignGrade(int score, int numQues)
{
double percentScore = static_cast<double>(score) / (numQues * 2); // calculate the score percentage
cout << "Score: " << percentScore * 100 << "%" << endl; // display the score
if (percentScore >= 0.9) // if score is greater than or equal to 90%, return A
return 'A';
else if (percentScore >= 0.8) // if score is greater than or equal to 80%, return B
return 'B';
else if (percentScore >= 0.7) // if score is greater than or equal to 70%, return C
return 'C';
else if (percentScore >= 0.6) // if score is greater than or equal to 60%, return D
return 'D';
else // any score lower thn 60%, return F
return 'F';
} // end assignGrade function
It keeps breaking here in the debugger:
static void __CLRCALL_OR_CDECL assign(_Elem& _Left, const _Elem& _Right)
_NOEXCEPT
{ // assign an element
_Left = _Right;
}
// Redo Programming Exercise Six of Chapter Eight
// Using Dynamic Arrays -- C++ Advanced
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
// function prototype
void readFile(ifstream& inFile, string fileName);
int main()
{
// variables, pointers and dynamic arrays
int numStud = 200; // stores the number of students, max students was 200
int numQues = 20; // stores the number of questions on test
string *studentIDs; // pointer variable for studentIDs dynamic array
char *correctAnswers; // pointer variable for correctAnswers dynamic array
correctAnswers = new char[numQues]; // correctAnswers dynamic char array
char *studentAnswers; // pointer variable for studentAnswers dynamic array
studentAnswers = new char[numQues]; // studentAnswers dynamic char array
char *fileName; // pointer variable for fileName dynamic char array
fileName = new char[25]; // fileName dynamic char array
ifstream inFile; // input stream variable inFile
// display message to explain the program
cout << "\nJames Flowers - Chapter 12 - Programming Exercise 2" << endl;
cout << "\nRedo Programming Exercise Six of Chapter Eight\nUsing Dynamic Arrays..." << endl;
// request file name for fileName dynamic char array
cout << "\nPlease Enter the File Name (Ch12_Ex2Data.txt): ";
cin >> fileName;
cout << endl;
// call readFile function to read the file
readFile(inFile, fileName);
// request number of students for studentIDs dynamic char array and some calculations
cout << "\nHow many students took this test? (4): ";
cin >> numStud;
cout << endl;
studentIDs = new string[numStud]; // create studentIDs dynamic char array
inFile.getline(correctAnswers, '/n'); // read the correct answers first
for (int i = 0; i < numStud; i++) // loop students
{
inFile >> studentIDs[i]; // get the student ID
inFile.get(); // discard the blank space
inFile.getline(studentAnswers, '/n'); // get the student's test answers
cout << "Student ID: " << studentIDs[i] << endl; // output student id
int score = 0; // declare and initialize score to zero
cout << "Answers: "; // display "Answers: "
for (int j = 0; j < numQues; j++) // loop each question
{
cout << studentAnswers[j]; // output student's answers
if (studentAnswers[j] == correctAnswers[j]) // if student answer is correct
score += 2; // add 2 to score
else if (studentAnswers[j] != correctAnswers[j] && studentAnswers[j] != ' ') // incorrect answer but not blank
score -= 1; // subtract 1 from score
else if (studentAnswers[j] == ' ') // if question left blank
score -= 0; // nothing subtracted from score
studentAnswers[j] = ' '; // clear each indice for next student
}// end for
cout << endl; // new line, housekeeping
char grade = 0; // char variable grade initialized to 0
double percentScore = static_cast<double>(score) / (numQues * 2); // calculate the score percentage
cout << "Score: " << percentScore * 100 << "%" << endl; // display the score
if (percentScore >= 0.9) // if score is greater than or equal to 90%, return A
grade = 'A'; // grade = A
else if (percentScore >= 0.8) // if score is greater than or equal to 80%, return B
grade = 'B'; // grade = B
else if (percentScore >= 0.7) // if score is greater than or equal to 70%,
grade = 'C'; // grade = C
else if (percentScore >= 0.6) // if score is greater than or equal to 60%,
grade = 'D'; // grade = D
else // any score lower than 60%,
grade = 'F'; // grade = F
cout << "Grade: " << grade << "\n" << endl; // display grade
}// end for
system("pause"); // pause for readability
return(0);
}// end main
// readFile function reads the file, if not displays error message
void readFile(ifstream& inFile, string fileName)
{
inFile.open(fileName); // use inFile to open input file
if (!inFile.is_open()) // if the file can't be opened or it is corrupt
{
cout << "There was an error opening the input file...\nPlease check file name and try again!\n" << endl; // display error message
system("pause"); // pause for readability
exit(1);
}// end if
} // end readFile function

cin unintentionally skipping user input

I am trying to write a loop that validates user input, and then repeats if the input is bad. The input must be either a binary number (as a string) or a decimal number (as an int). I have seperate functions to validate this input, but they are not causing any trouble.
The problem arises when I select 1 or 2, and then willingly enter an invalid binary or decimal number. At this point, the do-while loop repeats successfully. The program prints another request for user input to cout, But when it comes time for the user to enter input, the program thinks that there is input in the console before I even enter anything. I believe this is a problem with whitespace/control characters in the buffer, but I am not sure how to fix it. I have tried using std::cin >> std::ws to clear any straggling white space, but no luck.
#include <iostream>
#include <string>
#include <limits>
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
using std::cout;
using std::cin;
using std::endl;
using std::numeric_limits;
using std::max;
using std::streamsize;
using std::string;
//int toDecimal;
//true is is binary
bool validateBinary(const string &binaryNumber){
for(int i = 0; i < binaryNumber.length(); i++){
if((binaryNumber[i] != 1) && (binaryNumber[i] != 0)){
return false;
}
}
return true;
}
//true if is decimal
bool validateDecimal(){
return cin;
}
int main() {
int conversionType = 0; //we initialize conversionType to a default value of 0 to ensure the copiler it will always have a value
bool isBinary = false;
bool isDecimal = false;
string binaryNumberInput;
int decimalNumberInput;
do {
if(conversionType == 0){
cout << "Enter 1 to convert binary to decimal," << endl;
cout << "2 to convert decimal to binary, " << endl;
cout << "or 3 to exit the program: ";
std::cin >> std::ws; //to clear any whitespace fron cin
cin >> conversionType; //upon a second iteration, this value is read in before a user input is given
}
if(!cin || (conversionType != 1 && conversionType != 2)){
cout << "Incorrect input." << endl;
cin.clear(); //clear the fail bit
cin.ignore(numeric_limits<streamsize>::max(), '\n'); //used to ignore not-numeric input
}
cout << "You have selected option " << conversionType << "." << endl;
if(conversionType == 1){
cout << "Please enter a binary number: ";
cin >> binaryNumberInput;
isBinary = validateBinary(binaryNumberInput);
if(!isBinary){
cout << "The numbered you entered is not a binary number!" << endl;
conversionType = 0;
}
}
if(conversionType == 2){
cout << "Please enter a decimal number: ";
cin >> decimalNumberInput;
isDecimal = validateDecimal(); //true if succeeded, meaning is a number
if(!isDecimal){
cout << "The numbered you entered is not a decimal number!" << endl;
conversionType = 0;
}
}
}
while((conversionType != 1 && conversionType != 2) || (isBinary == isDecimal));
return 0;
}
Rather than debug your current program you might want to consider using the standard library to simply things
#include <iostream>
#include <string>
#include <bitset>
#include <climits>
#include <limits>
template<typename T>
void get(T& value)
{
while (!(std::cin >> value)) {
std::cout << "Invalid input\n";
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
int main()
{
std::cout << "Enter 1 to convert binary to decimal,\n" <<
"2 to convert decimal to binary\n";
int option;
if (std::cin >> option) {
switch (option) {
case 1: {
std::bitset<CHAR_BIT * sizeof(unsigned long long)> bits;
get(bits);
std::cout << bits.to_ullong() << '\n';
break;
}
case 2: {
unsigned long long i;
get(i);
std::cout << std::bitset<CHAR_BIT * sizeof i>(i) << '\n';
break;
}
}
}
}
If you want this to loop you should be able to add it back in again easily enough.

Getting a 0 in all my calculations when inputting values, but the math works out on paper. No errors or warnings from compiler

Okay I'm not exactly sure where I'm going wrong here, but any kind of help would be vastly appreciated. I When i input the values for the pay rate and the hours worked each week (which is wk1-wk5), i am getting a zero for all my calculations.
Here is source Code:
#include <iostream>
using namespace std;
const double tax = 0.14;
int main()
{
int wk1,wk2,wk3,wk4,wk5;
wk1 = wk2 = wk3 = wk4 = wk5 = 0;
double payrate;
payrate = 0;
cout << "Please enter the payrate for employee." << endl;
cin >> payrate;
cout << "Please enter employee's total hours for week one:" << endl;
cin >> wk1;
cout << "Please enter employee's total hours for week two:" << endl;
cin >> wk2;
cout << "Please enter employee's total hours for week three:" << endl;
cin >> wk3;
cout << "Please enter employee's total hours for week four:" << endl;
cin >> wk4;
cout << "Please enter employee's total hours for week five:" << endl;
cin >> wk5;
int thours = wk1 + wk2 + wk3 + wk4 + wk5;
thours = 0;
double gross = payrate * thours;
double taxes = tax * gross;
double net = gross - taxes;
double clothes = 0.10 * net;
double supplies = 0.10 * net;
double remaining = net - clothes - supplies;
double bonds = 0.25 * remaining;
double pbonds = 0.50 * bonds;
cout << "Here is income before taxes: " << gross << endl;
cout << "Here is income after taxes: " << net << endl;
cout << "Here is clothes and accesories: " << clothes << endl;
cout << "Here is School supplies: " << supplies << endl;
cout << "Here is personal bonds: " << bonds << endl;
cout << "Here is parents bonds: " << pbonds << endl;
return 0;
}
You incorrectly assume that by assigning an expression such as double x= y*3 to a variable, that its value will always be determined by the value of y throughout your program. That's not the case.
What this does is that the value in y is copied, multiplied by 3 and then assigned to x. So if at the time of assignment, y was 10, it will always be 10 no matter how y changes in the future unless you reassign x with the new value of y.
So in order to solve your problem, perform the calculations after you receive the values of your variables.
+
Also, this line:
int thours = wk1 + wk2 + wk3 + wk4 + wk5;
thours = 0;
After you assign the wk variables to thours, you set it back to zero. What you should be doing:
int thours = 0;
thours = wk1 + wk2 + wk3 + wk4 + wk5;

C++ Using Pointers within a Structure (Struct)

I am trying to create a program that asks a user how many babies they have, gather input about each baby, and then displays it on the console. I am 90% of the way there but I am stuck.
The input/output on the console should look like this;
Please enter the number of babies: 2
Please enter baby #1's height : 21.5
Please enter baby #2's height : 19.75
Baby #1's info:
Height: 21.5 inches
Baby #2's info:
Height: 19.75 inches
The output for my code keeps showing 19.75 as the height for both babies. I realize I probably need to use a pointer to dynamically allocate different values to aBaby.height, but I haven't used a pointer within a structure before. Any help would be greatly appreciated.
#include <iostream>
using namespace std;
struct Baby {
double length;
};
int main ()
{
int iNumBaby = 0;
cout<<"Please enter the number of babies: ";
cin>>iNumBaby;
cout<<endl;
Baby aBaby;
Baby* pBaby = new Baby[iNumBaby];
for(int i = 0; i < iNumBaby; i++)
{
cout << "Please enter baby #"<< i + 1 <<"'s height <inches>: ";
cin >> aBaby.length;
cout << "\n";
}
for(int i = 0; i < iNumBaby; i++)
{
cout << "\Baby #"<<i + 1<<"'s info:\n";
cout << "Height: " <<aBaby.length<<" inches"<<endl;
cout << "\n";
}
system("PAUSE");
delete[] pBaby;
return 0;
}
It's nothing to do with pointers, you simply have a bug in your code. See the following block:
for(int i = 0; i < iNumBaby; i++)
{
cout << "Please enter baby #"<< i + 1 <<"'s height <inches>: ";
cin >> aBaby.length;
cout << "\n";
}
The main problem here is that you are storing the entry into aBaby.length every time. In fact, you never used pBaby anywhere in your code. I assume this is what you want:
for(int i = 0; i < iNumBaby; i++)
{
cout << "Please enter baby #" << i + 1 << "'s height <inches>: ";
cin >> pBaby[i].length;
cout << "\n";
}
for(int i = 0; i < iNumBaby; i++)
{
cout << "Baby #" << i + 1 <<"'s info:\n";
cout << "Height: " << pBaby[i].length << " inches" << endl;
cout << "\n";
}
for(int i = 0; i < iNumBaby; i++)
{
cout << "Please enter baby #"<< i + 1 <<"'s height <inches>: ";
cin >> aBaby.length;
cout << "\n";
}
the problem lies in your assignment to aBaby.length. You are assigning every baby's length to the same object. Try accessing the array of babies that you created and change the length of those.
Example:
cin >> pBaby[i].length

Why am I getting an assertion error?

#include <iostream>
using namespace std;
int main ()
{
int size = 0;
int* myArray = new int [size + 1];
cout << "Enter the exponent of the first term: ";
cin >> size;
cout << endl;
for (int i = size; i >= 0; --i)
{
cout << "Enter the coefficient of the term with exponent "
<< i << ": ";
cin >> myArray[i];
}
for (int i = size; i >= 0; --i)
{
cout << i << endl;
}
return 0;
}
Why am I getting an assertion error on input greater than 2? This is the precursor to a polynomial program where the subscript of the array is the power of each term and the element at array[subscript] is the coefficient.
Your array is allocated to be an int[1]. It needs to be allocated after you read in the size value.
You are initializing your array when size = 0, giving an array size of 1
You get your assertion error when you go outside of the array bounds (1).
myArray always has size 0 + 1 = 1. i starts out at whatever the user inputted, and the first array access you make is myArray[i]. So, say the user inputs 5, your array has size 1 and you access myArray[5]. It will fail!
I would allocate the array AFTER you input size.

Resources