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
Related
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
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
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;
I am using a vector to represent a deck of cards in c++. I am having trouble shuffling the deck and removing the first element.
Shuffling does not work, the vector keeps the same order. I call reseed once in my program, in the constructor of Deck. int random is different every time. I have tried time(NULL) and time(0). Shuffling:
void Deck::reseed() {
srand(time(NULL));
}
void Deck::shuffle() {
int random = rand();
for(int i = 0; i < random; i++) {
std::random_shuffle(deckVec.begin(), deckVec.end());
}
}
Removing does not work, the last element is removed instead of the first (for example, element 16 is erased and not element 0). Removing:
Card Deck::dealCard() {
//other code...
Card& tempCard = deckVec.front();
std::vector<Card>::iterator temp = deckVec.begin(); //This if for debugging, and
//this pointer is correct
deckVec.erase(deckVec.begin());
return tempCard; //the correct card is returned
}
Any help would be appreciated.
-----------Update----------------
code for printing before and after shuffle:
cout << deck.toString(); //output: Suit: Clubs, Rank: 2
// Suit: Clubs, Rank: 3 ...
//shuffle if there are three arguments
if(argc == 3)
deck.shuffle();
cout << deck.toString();//output: Suit: Clubs, Rank: 2
// Suit: Clubs, Rank: 3 ... (identical to above)
It's difficult to show dealCard. Basically, I call it here:
void operator<<(Hand& hand, Deck& deck) {
hand.addCard(deck.dealCard());
}
Then I print out the contents. The output is: C2 C2 C2 C2 ... for the 2 of Clubs. They are all the first card in the deck.
for(int i = 0; i < 5; i++) {
for(unsigned int j = 0; j < hands.size(); j++) {
try {
hands.at(j) << deck;
} catch(int& i) {
cout << "no cards left" << endl;
}
}
}
//print out the contents
cout << deck.toString() << endl;
for(unsigned int i = 0; i < hands.size(); i++) {
cout << "Hand " << i << ": ";
cout << hands.at(i).toString() << endl;
}
#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.