Simple code is displaying absurdly large numbers...? - visual-c++

I have run this program before and it worked fine. Then I added the "if" statements to the "set" methods and i started seeing very large numbers when I ran the program. What can I do to fix this problem or can someone enlighten me as to why this is happening?
class GradeBook{
public:
void setStudentID(int ID){
if(10000 <= studentID && studentID <= 50000){
studentID = ID;
}
}
int getStudentID(){
return studentID;
}
void setStudentGrade(int grade){
if(0 <= studentGrade && studentGrade <= 100){
studentGrade = grade;
}
}
int getStudentGrade(){
return studentGrade;
}
void displayMessage(){
cout << "Student " << getStudentID() << " has a score of " << getStudentGrade() << endl;
}
private:
int studentGrade;
int studentID;
};
int main(){
int nameOfID;
int nameOfGrade;
GradeBook gb;
cout << "Please enter a student ID: " << endl;
cin >> nameOfID;
gb.setStudentID(nameOfID);
cout << "Please enter the student's grade: " << endl;
cin >> nameOfGrade;
gb.setStudentGrade(nameOfGrade);
getchar();
gb.displayMessage();
getchar();
}

You have your comparisons wrong you meant.
if(10000 >= studentID && studentID <= 50000)
You don't have else statements to make sure the variable is initialized, thus I'd change it to:
if(10000 >= studentID && studentID <= 50000){
studentID = ID;
}
else{
studentID = 0; //or whatever value you want to mean invalid
}
That will hopefully fix your issues.

Two guesses (I'm not that good in C++):
Your variables aren't initialized; if the if-expression does not evaluate to true the private variables will never be set to anything. The "large numbers" would just be the random value that happened to be in the memory where the variable is stored.
You are reading strings with cin and passing their pointers into the set-methods. The "large numbers" would actually be (some garbled representation probably) of the pointer-address.
Edit: Actually, forget 2; this seems to suggest that it should work. My C++ is somewhat rusty ;-)

The first thing I noticed is that your ivars are not being initialized so if the input in the setters doesn't validate then the behavior you've identified is to be expected.
You should create a default constructor and initialize the two variables to 0.

when you define GradeBook gb, the private fields (studentGrade and studentID) are not initialized. Then, gb.setStudentID tries to read studentID. studentID would be random value.

Related

My code is stuck in an infinite loop in 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

Trying to make a simple client sided chatbox; giving me a cout problem

I am almost completely new to c++ and have been trying to create a simple client sided chat box just to test but have come across the problem that the output of my cin gives only the first letter of the name given.
~ Jayden
I've tried declaring the "userName" as a bool, int and char however two of these give the cout a number as the outcome. I have youtubed this but it seems like it's a noob problem so no one has an answer from what I've seen.
#include <iostream>
#include <string>
using namespace std;
int main()
{
int userName;
bool nameSuccess = false;
cout << "Welcome to ChatBox v1.43" << endl;
cout << "========================" << endl;
do {
cout << "Enter a username: ";
cin >> userName;
cout << "You will now be known as ";
cout << userName;
nameSuccess = true;
} while (!nameSuccess);
system("pause");
cin.ignore();
cin.clear();
cin.get();
return 0;
}
The console should output the user name in this format : "You will now be known as (userName)"
int userName;
This should be.
string userName;
As a name is a string, not an integer.
The type of a variable is super important in C++. So you should definitely take the time and look up what int, char, bool mean. Once you have done that you will see why none of them work for a name.

Do while loop won't break

I am making a Goldilocks game. If the user chooses the wrong answer it would loop back to the beginning of the program. When I try to choose any option it always loops back to the beginning including the correct answer which is 2. I am still new to c++. I do not understand why it is looping to the beginning if the condition is true when 2 is chosen.
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
void FirstSet()
{
bool win = false;
string PName;
int choice;
int num1, num2, result;
do
{
system("CLS");
cout << " Please Enter Name \n";
cin >> PName;
cout << PName << " and the Three Bears\n\n ";
cout << PName << " Walks up and sees 3 Doors, 1 Large Door, 1 Medium
Door and 1 Small Door. \n\n\n " << "Which Door do you want to Open?\n "
<< " 1 for The Large Door\n " << " 2 for the Medium Door\n " << " 3
for the small door\n ";
cin >> choice;
if (choice == '1')
{
cout << " The large door is too heavy it will not budge.\n "
<< " Please Try Again\n\n ";
system("pause");
}
else if (choice == '2')
{
win = true;
}
else if (choice == '3') {
cout << " The Door is too small you would get stuck.\n "
<< "Please Try Again\n\n";
}
} while (!win);
}
int main()
{
FirstSet();
system("pause");
return 0;`
The reason none of your comparisons are turning true is because you are reading the input into an int variable. Then you are comparing to ascii character values of 1,2 and 3 which happen to be 49, 50 and 51 respectively. If you modify your if lines to compare directly with integers, it should work:
if (choice == 1)
{
...
}
else if (choice == 2)
{
...
}
else if (choice == 3)
{
...
}
Although, for readability purposes and also to avoid such cases, I recommend using switch case statements in this case.

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

how to write class with data members and member function c++

hi guys i would like u to help me in my assignment i had try to solve it but there are some of the things that making me :s i knw how to creat the name and id
string Name;
int Id;
bt wt does it mean a pointer to a dynamically allocated array of grades:s:s:S?
i jst knw how to declare a pointer like : double* Grades;
here is the assignment......
Create a Class StudentGrades with the following Data members:
Name : type String
Id: type integer
Grades: a pointer to a dynamically allocated array of Grades. Type is: pointer to double (* double)
It includes the following member functions:
A No-argument Constructor
A Constructor that takes two arguments : a String and an Integer and initializes the Name with the String and the ID with the Integer.
Set and get functions for Name, ID
A print function for Student information. It prints name, Id and the grades.
An overloaded Assignment operator of the Class Objects
A Copy Constructor of the Class Objects
Use the Syntax for the copy constructor and the overloaded assignment operator.
In another file create a C++ program that prompts the user for data to create four objects of the class StudentGrades. The first object (std1) has 5 grades, and the second (std2) has 6 grades and the third (std3) has 4 grades and fourth (std4) has no grades and data.
Then copy std2 into std4 and assign std1 to std3. Then print the details of the four objects
hey i solved my assignment bt iam trying to running it bt it doesn't work can any body please tell me where the problem is n the program
#include <iostream>
using namespace std;
class student_grades{
private:
string name,n;
int Id,i;
double* grades[];
public:
student_grades();
student_grades(sting, int);
student_grades(const student_grades&);
void set(string name,int Id){
cout << "enter the name and the ID";
cin >> n >> i;
n = name;
i = Id;
}
void get(){
return i;
return n;
}
void student_grades (student_grades&opr){
name = name.opr;
Id = Id.opr;
grades[] = grades[].opr;
}
void student_info(){
cout << "the name of the student is:" << name;
cout << "the id for the srudent is:" << Id;
grades = new double[];
cout << "the grades of the student is:" << grades[] << endl;
delete []grades;
}
};
student_grades::student_grades() {}
student_grades::student_grades(string name, int Id) {
name=" ";
Id=0;
}
student_grades::student_grades(const student_grades& copy) {
name=copy.name;
Id=copy.Id;
}
int main() {
student_grades std1;
std1.set();
cin >> std1.grades[5];
std1.get();
student_grades std2;
std2.set();
cin >> std2.grades[6];
std2.get();
student_grades std3;
std3.set();
cin >> std3.grades[4];
std3.get();
student_grades std4;
std4.set();
cin >> std4.grades[];
std4.get();
std1 = std3;
std2 = std4;
cout << std1 << std2 << std3 << std4;
return 0;
}
A dynamically allocated array is an array that isn't given a specific size until run time, unlike a fixed array declaration is at compile time. A declaration of a fixed array looks like:
int grades[500];
That array will allocate memory for 500 integers and stay that way unless you destroy it or resize it.
Creating a dynamically allocated array would look more like this:
int* grades = NULL; // A declaration in your StudentGrades class
int n = <get size from somewhere>; // Makes the size "dynamic"
grades = new int[n]; // This definition could be in your StudentGrades ctor,
// with n being a parameter.
Then you could continue by initializing all of the array elements to 0 or fill up your array with other values as needed. When you're done with the array, clean it up. This could be in your destructor:
delete [] grades;
grades = NULL;

Resources