GPA calculator crash bug in c++ - c++

I am a noob in programming and was told that to learn more, I need to do some project and so I started this GPA calculator that eventually prints your GPS in both 5 unit and it 4 unit equivalent.
The problem is I created an array to hold the grade point from A-F and another array to hold the letter grade from 0-5, but after I was done it performed well until I noticed it crashes when I try to calculate for more than 6 courses, I have tried what I can do but still can't detect the bug and solve the problem all to no avail.
#include<iomanip>
#include <iostream>
using namespace std;
int main(){
int numOfCourse;
cout<<"insert the number of courses offered: ";
cin>>numOfCourse;
int scores[numOfCourse];//an array that stores the number of course inputed by the user
int creditUnit[numOfCourse];//another array that stores the credit unit of the user
int qualityPoint[numOfCourse];//this is gotten by multiplying the credit unit by grade point
int totalQualityPoint=0;
int totalCreditUnit=0;
int gradePoint[6];//predefined grade point 0-5
string letterGrade[6];//predefined letter grade A-F which corresponds with the grade point
float gradePointAverage5;//5 point GPA Scale
float gradePointAverage4;// 4 point GPA Scale
// Asks the user to input scores and credit load of the courses
for (int i=0; i< numOfCourse; i++){
cout<<"input the scores of the course: ";
cin>>scores[i];
cout<<" input the credit load of the course: ";
cin>>creditUnit[i];
//defining the gradepoint and its corresponding letter grade
if(scores[i] <= 39){
gradePoint[i]=0;
letterGrade[i] = "F";
} else if (scores[i] >=40 && scores[i] <= 44){
gradePoint[i]=1;
letterGrade[i] ="E";
} else if (scores[i] >=45 &&scores[i]<= 49){
gradePoint[i]=2;
letterGrade[i] = "D";
}else if (scores[i] >=50 &&scores[i] <= 59){
gradePoint[i] =3;
letterGrade[i] = "C";
}else if (scores[i] >=60 &&scores[i] <= 69){
gradePoint[i]=4;
letterGrade[i] = "B";
}else if (scores[i]>=69 &&scores[i] <= 100){
gradePoint[i]=5;
letterGrade[i] = "A";
}else{
cout<< "Your grade is incorrect"<<endl;
return 0;
}
}
cout<<"Scores Letter Credit Grade QualityPoint"<<endl;
cout<<" Grade Unit Point (CU * GP)"<<endl;
for(int i =0; i<numOfCourse;i++){
qualityPoint[i] = creditUnit[i] * gradePoint[i];
cout<<scores[i] <<" "<<letterGrade[i]<<" "<<creditUnit[i]
<<" "<<gradePoint[i]<< " "<<qualityPoint[i]<<endl;
totalQualityPoint=totalQualityPoint + qualityPoint[i];
totalCreditUnit=totalCreditUnit + creditUnit[i];
gradePointAverage5= float(totalQualityPoint)/float(totalCreditUnit);
gradePointAverage4 = (gradePointAverage5/5)*4;
}
cout<< "Your total Quality Point is: "<<totalQualityPoint<<endl;
cout<< "Your total Credit Unit is: "<<totalCreditUnit<<endl;
cout<< "Your Grade Point Average (GPA) on the 5 point scale is : "<<setprecision(2)<<fixed<<gradePointAverage5<<endl;
cout<< "Your Grade Point Average (GPA) on the 4 point scale is : "<<setprecision(2)<<fixed<<gradePointAverage4<<endl;
}

Related

C++ Function Assignment grade calculator

my programming lecturer is teaching us how to write functions, terribly I might add, We are to make a program that calculates the grade of a students work. Here are the specs on it.
score 1 is weighted by 0.3,
score 2 is weighted by 0.5, and
score 3 is weighted by 0.2.
If the sum of the scores is greater than or equal to 85 then the Grade is an 'A'.
If the sum of the scores is greater than or equal to 75 then the Grade is a 'B'.
If the sum of the scores is greater than or equal to 65 then the Grade is a 'C'.
If the sum of the scores is greater than or equal to 50 then the Grade is a 'P'.
Otherwise the Grade is an 'F'.
So I wrote my code as follows:
#include <iostream>
using namespace std;
void calculateGrade() {
int score1, score2, score3;
int percentDec;
cin >>score1>>score2>>score3;
percentDec = (score1+score2+score3);
if (percentDec >= 85) {
cout << "The Course grade is: A";
}
else if (percentDec >= 75) {
cout << "The Course grade is: B";
}
else if (percentDec >= 65) {
cout <<"The Course grade is: C";
}
else if (percentDec >= 50) {
cout <<"The Course grade is: P";
}
else {
cout <<"The Course grade is: F";
}
} //end of calculateGrade()
int main() {
calculateGrade();
return 0;
}
Which works fine on my IDE but when I put it into the program which determines whether our answer is correct it doesn't work, that is because ordinarily we are asked only to put the stuff in main() but because it is a function and it's not in the main() it doesn't work like that. We are given this as an example and I'm about to throw something with how dumb this is. I don't know how to program it to work the way they want it.
cout << "The Course grade is: " << calculateGrade(90, 50, 99) << endl;
Cheers for any help.
This is not a forum for getting answers to your homework questions, although good job on showing what you have tried. Here are areas to look at:
1) The instructor is showing you that you can decompose code into functions. He/she wants you to wrtie a function calculateGrade that would work like this cout << "The Course grade is: " << calculateGrade(90, 50, 99) << endl;. Now every function declaration in C++ has three parts to it:
return_type functionName(param1_type param1, param2_type param2,...) {
// implementation
}
The functionName is what the function is referred to by (calculateGrade in this case), the parameters are the information you need to pass to the function for it to do its thing, and the return type is what the function will give back. In this case, your instructor is saying calculateGrade will take three integers as parameters and must return a string representing the grade of the student's scores. Thus your function should look like:
string calculateGrade(int score1, int score2, int score3) {
// ...
}
2) As the comments rightly pointed out, you aren't multiplying score1, score2, and score3 by their respective weights in the calculateGrade() method.
From your question and comments, I get the feeling your grasp of functions is not completely solid. Rather than complaining about your teacher (be it his/her fault or not), I suggest you read here about it. There are a plethora of online resources that will help you learn the basics of C++ programming.
You tutor is asking you to write a function which accept 3 parameter and return the grade.
char calculateGrade(int score1, int score2, int score3) {
char grade = 'F';
double percent = (0.3*score1 + 0.5*score2 + 0.2*score3);
if(...) {
grade = 'A/B/C/P'; // Depending upon condition, assign only value
}
else if(...) {
grade = 'A/B/C/P'; //Depending upon condition, assign only one value
}
// Add the condition in if else statements to get the actual grade.
return grade;
}
Note that the percent is of type double. You need to do all comparison in if else on double basis.

Having trouble with simple c++ program using decimals.

//Purpose: To calculate the price to pay an author
//Programmer: Brandon C Ballard
//Last Updated: 2/20/2014
#include <iostream>
#include <cstdlib>
using namespace std;
//function prototype
float TotalPay(int numWords, char Level);
int main()
{
float TotalPay;
int numWords;
char Level;
int amtToPay;
cout << "Please enter number of words: ";
cin >> numWords;
cout << endl;
cout << "Please enter a Level, A,B, or C: ";
cin >> Level; cout << endl << endl;
//calculate price per word
if (numWords < 7500)
amtToPay = numWords * .08;
else if (numWords >= 7500 && numWords < 8000)
amtToPay = 600;
else if (numWords >= 8000 && numWords < 17500)
amtToPay = numWords * .075;
else if (numWords >= 17500 && numWords < 19000)
amtToPay = 1313;
else
amtToPay = numWords *.07;
//calculate the Level of the author
if (Level == 'C' or Level == 'c')
Level = 1;
else if (Level == 'B' or Level == 'b')
Level = 1.25;
else if (Level == 'A' or Level == 'a')
Level = 1.75;
TotalPay = amtToPay * Level;
cout << "Length of Story (words): "; cout << numWords; cout << endl << endl;
cout << "Amount Due Author: "; cout << "$"; cout << TotalPay; cout << endl << endl << endl;
system("PAUSE");
return 0;
}//end main function
My instructor wants me to write a program that can calculate the amount of money to pay an author who is submitting an article to a magazine. The amount of money to pay the author is based off of how many words are in the article. It works like this...
-if length (in words) is less than 7,500: the author gets paid $0.08 per word.
-if length is 7,500 to 8,000: the author gets paid a fixed $600.
-if length is 8,000 to 17,500: the author gets paid $0.075 per word.
-if length is 17,500 to 19,000: the author gets paid a fixed $1313.
-if length is greater than 19,000: the author gets paid $0.08 per word.
Also: There are three different "Levels" of authors (A,B, and C). A "C" Level author (new author) would get paid based on the information above. A "B" Level author (established writer) would get paid 1.25 times the amount of a Level C author. An "A" Level author (rockstar) would get paid 1.75 times the amount of a Level C author.
The Math: Basically, I wrote the program so that it first calculates the amount to pay the author (amtToPay). Then, it calculates what the (Level) is equal to. Then the (TotalPay) is the (amtToPay) multiplied by the (Level).
My Problem: Everything works great except for the part where it //calculates the Level of the author. For example, if I were to input the author as an "A" Level, he should get paid 1.75 times that of a Level C author. So, it should multiply the (amtToPay) by 1.75, except what is actually doing is multiplying it by "1" and is ignoring the ".75".
I am new to programming and I understand that there are probably many other ways to write this. But please try and help me the best that you can. Thank you.
Level is an integer type so when you assign the floating point numbers to it, the fractional parts are dropped.
Try defining double rateLevel and then
if (Level == 'C' or Level == 'c')
rateLevel = 1;
else if (Level == 'B' or Level == 'b')
rateLevel = 1.25;
else if (Level == 'A' or Level == 'a')
rateLevel = 1.75;
TotalPay = amtToPay * rateLevel;
The proper way to do this is to not use floating point types at all, except maybe for printouts. The way to accomplish this is to scale everything by a power of ten that will remove all fractional components from your values. In your code the least significant digit is in the thousands place (0.075). This means that you need to multiply all your values by 1000. This is called your scale factor. Then you can do your math using only integral types, int, long, int64_t, etc. At the end of your calculations you can split the results into whole number and fractional components.
Like this:
int TotalPayDollars = TotalPay/1000;
int TotalPayMilliDollars = TotalPay - 1000*TotalPayDollars;
int TotalPayCents = (int)((double)TotalPayMilliDollars/10 + 0.5);
The first line is all integer math so the dividing by 1000 discards any fractional parts.
The second line finds the difference between your original value and the truncated value. We multiply TotalPayDollars by 1000 to bring it into the same units as TotalPay again.
In the last line the + 0.5 works to round up to the nearest cent.
NOTE: when choosing a scale factor it is very important to make sure that you don't overflow your integer type. A 32 bit signed integer can only hold numbers up to 2^31-1 (2,147,483,647). If any of your calculations will go higher than that value then you should use a 64 bit integer type.
Level is type char which is integral, you should create a new variable specifically to hold the amount boosted by level:
double level_boost;
//logic
Totalpay = amtToPay * level_boost;
PS: in your logic, you do not have to use &&:
if (numWords < 7500)
amtToPay = numWords * .08;
else if (numWords < 8000)
//if the numwords is less than 7500 will be handled by first if
amtToPay = 600;

Sorting Array's of Structs

I am working on an assignment for my C++ class (the assignment is pasted at the bottom of my test.cpp file). I implemented everything correctly up until the last requirement (using a sort_name function, sort the student structures based on their last names and for each student, sort the classes he or she is taking based on class title. Display the sorted list of students using the display function by calling it from main). I have attempted to implement my sort function by sorting just the students at first, but I keep getting errors and getting stuck(The current error is: Unhandled exception at 0x777a15de in 839a4 Vasilkovskiy.exe: 0xC00000FD: Stack overflow). Any help would be greatly appreciated.
NOTE: I understand that vectors are much more useful for sorting, but our professor does not want us to use them.
#include <iostream>
#include <string>
#include <stdio.h>
#include <string.h>
#include <iomanip>
using namespace std;
struct Class
{
string title;
int units;
char grade;
};
struct Student
{
string name;
double gpa;
Class classes[500];
};
int const SIZE = 50;
void initStudent(Student[], int);
void readStudent(Student[], int, int&);
void gpaCalculate(Student&);
void print(Student[], int);
void sort_name(Student[], int);
void swapStus(Student&, Student&);
void stringToCharArray(string, char[]);
int locactionOfFirstName(Student[], int, int);
int main()
{
int numberOfStudents = 0;
Student students[SIZE];
initStudent(students, SIZE);
readStudent(students, SIZE, numberOfStudents);
for(int i = 0; students[i].name != "";i++)
gpaCalculate(students[i]);
print(students, numberOfStudents);
sort_name(students, numberOfStudents);
system("pause");
return 0;
}
void initStudent(Student st[], int s)
{
for(int i = 0; i < s; i++)
{
st[i].gpa = 0.0;
}
}
void readStudent(Student st[], int s, int& nStus)
{
for(int i = 0; i < s; i++)
{
string tmpName;
cout << "Enter student name: ";
getline(cin, tmpName);
if(tmpName == "")
break;
st[i].name = tmpName;
nStus++;
for(int j = 0; j < 500; j++)
{
string tmpTitle;
cout << "Enter class title: ";
getline(cin, tmpTitle);
if (tmpTitle == "")
break;
st[i].classes[j].title = tmpTitle;
cout << "Enter units for " << st[i].classes[j].title << ": " ;
cin >> st[i].classes[j].units;
cout << "Enter grade for " << st[i].classes[j].title << ": " ;
cin >> st[i].classes[j].grade;
cin.ignore();
}
}
}
void gpaCalculate (Student& s)
{
double unitsByPoints = 0;
double totalUnits = 0;
for (int i = 0; s.classes[i].title != ""; i++)
{
int grade = 0;
char ltrGrade = s.classes[i].grade;
switch (ltrGrade)
{
case 'A':
grade = 4;
break;
case 'B':
grade = 3;
break;
case 'C':
grade = 2;
break;
case 'D':
grade = 1;
break;
case 'F':
grade = 0;
break;
}
unitsByPoints += s.classes[i].units*grade;
totalUnits += s.classes[i].units;
}
s.gpa = unitsByPoints/totalUnits;
}
void print(Student st[], int size)
{
for (int i = 0; i < size; i++)
{
cout << "Student's name: " << st[i].name << endl;
for (int j = 0; st[i].classes[j].title != ""; j++)
{
cout << st[i].classes[j].title << "," << st[i].classes[j].grade << endl;
}
cout << fixed << setprecision(2) << "GPA: " << st[i].gpa << endl;
}
}
//void sort_name(Student st[], int size)
//{
// for(int i = 0; i < size; i++)
// {
// int smallest = locactionOfFirstName(st, i, size);
// swapStus(st[i], st[smallest]);
// }
//
//}
void swapStus(Student& s1, Student& s2)
{
Student tempStu;
tempStu = s1;
s1 = s2;
s2 = tempStu;
}
void stringToCharArray(string s, char c[])
{
char tempCharArray[50];
for(int i = 0; s[i] != '\n'; i++)
{
tempCharArray[i] = s[i];
}
char * space = strstr(tempCharArray," ");
strcpy(c,space);
}
bool lastNameCompare(string l1, string l2)
{
char lName1[50];
char lName2[50];
stringToCharArray(l1, lName1);
stringToCharArray(l2, lName2);
return (strcmp(lName1, lName2) >=0);
}
int locactionOfFirstName(Student st[],int start, int size)
{
char lName1[50];
char lName2[50];
stringToCharArray(st[0].name, lName1);
int i;
for(i = start; i < size;)
{
stringToCharArray(st[i].name, lName2);
if(strcmp(lName1, lName2) >= 0 )
{
stringToCharArray(st[i].name, lName1);
}
}
return i;
}
void InsertItem(Student values[], int startIndex, int endIndex)
{
bool finished = false;
int current = endIndex;
bool moreToSearch = (current != startIndex);
while (moreToSearch && !finished)
{
if (lastNameCompare(values[current-1].name, values[current].name))
{
swapStus(values[current], values[current-1]);
current--;
moreToSearch = (current != startIndex);
}
else
finished = true;
}
}
void sort_name(Student values[], int numValues)
{
for (int count = 0; count < numValues; count++)
InsertItem(values, 0, count);
}
/*
Define a structure called Class (with uppercase C) with the following data:
title, units and grade.
Define a structure called Student with the following data:
name (full name), gpa, and classes which is an array of Class structures (all the classes the student has taken so far).
Write an initialize function that receives an array of Student structures and its size and sets the gpa of all to 0.0.
In main, create 50 Students and call the above function to initialize the gpa for all 50 Students to 0.0.
Then, pass the array of student structures and its size to a read function that will read student data from the user and store the entered data in the array of student structures. The user will enter student name followed by the class title, units and grade received for each class he or she has taken. When finished entering class information for a student, the user will just press Enter (an empty string) and to end entering more students, he or she will do the same for the student name.
Example:
Enter student name: Maria Gomez
Enter class title: English 101
Enter units for English 101: 3
Enter grade for English 101: A
Enter class title: Math 201
Enter units for Math 201: 4
Enter grade for Math 201: B
Enter class title: [User enters RETURN to indicate no more classes]
Enter student name: Kevin Duran
Enter class title: Poly Sci 101
Enter units for Poly Sci 101: 3
Enter grade for Poly Sci 101: A
Enter class title: Math 201
Enter units for Math 201: 4
Enter grade for Math 201: B
Enter class title: [User enters RETURN to indicate no more classes]
Enter student name: [User enters RETURN to indicate no more students]
Once all Studnets have been entered, pass each element of the array of Student structures (element by element) to a gpa function which will compute and return the gpa for each Student using the classes array within each Student structure which contains the units and grade for each class taken by the student. Store the gpa returned by the above function in the gpa member of the Student structures. GPA is calculated by multiplying the number of units for each class by the points received for that class, and then adding all these products together and dividing it by total number of units. The points received for a class is based on the grade: for A, it's 4; for B, it's 3; for C, it's 2; for D it's 1; and for F it's 0. For example, if a student has take 3 classes with 3, 4, and 3 units and has received A, B, and C for these classes, respectively, then, the GPA will be 3 x 4 + 4 x 3 + 3 x 2 / 10 = 3.0.
Print all students showing name, followed by all classes taken, the grade received and the gpa using a display function which receives the array and its size as parameters.
Then, using a sort_name function, sort the student structures based on their last names and for each student, sort the classes he or she is taking based on class title. Display the sorted list of students using the display function by calling it from main.
For example:
Kevn Duran
Poly Sci 101, A
Math 150, B
GPA: 3.0
Maria Gomez:
English 101, A
Math 201, C
GPA: 2.9
Robert Small
Comp Science 801, C
Comp Science 802, D
GPA: 1.9
Tom Wang
Comp Science 808, A
Comp Science 839, B
GPA: 3.5
Then, sort the students based on their GPA's using a sort_gpa function and print the list again using the display function.
Then, ask what to search for - name or gpa. If name is selected, read a student name from the user and, using a binary search function that takes the array, its size and the name to search for, finds the student and displays all of his or her information (name, gpa, units and list of classes taken).
Example:
Enter a student name: Robert Small
Robert Small:
Comp Science 801, C
Comp Science 802, B
GPA: 2.5
If GPA is selected, read a GPA and using another binary search find the student with the given GPA by passing the students array, its size and the GPA to search for. Display the name of the student with the specified GPA in main.
Example:
Enter GPA to search for: 2.5
Robert Small was found with the GPA of 2.5
If the name or GPA is not found, tell the user it was not found; e.g.: There was no student with a GPA of 2.5; or Robert Small was not found.
Then, pass the array of student atructures and the size to a stats function which will return the average of the GPA's of all students and through two reference parameters will output the student structures that have the minimum and maximum GPA's. Print the average GPA, as well as the names of the students who have the minimum and maximum GPA in main, like so:
Average GPA = 3.17
Robert Small has the minimum GPA of 2.5.
Tom Wang has the maximum GPA of 3.5.
Finally, read a maximum and minimum GPA from the user and pass the array of student structures and its size, as well as two other arrays of student structures of the same size to a function which will store all students with a GPA of above the minimum in the highGPA array and all those with a GPA below the maximum in the lowGPA array. Display the students stored in these two arrays by passing them each from main to the display function. In other words, the highlow function receives two uninitalized arrays of student structures and populates them based on the GPA criteria passed to it (minimum GPA and maximum GPA). Then, upon return to main, main passes each of these arrays to the display function to display them. For example, if the user enters 2.0 for the maximum GPA, the lowGPA array gets filled out with all those students who have a GPA of less than 2.0. Likewise, if the minimum GPA is 3.5, the highlow function populates the highGPA array with those students who have a GPA of 3.5 or higher.
Example:
Enter maximum GPA: 2.0
Enter minimum GPA: 3.5
Students with a GPA of lower than 2.0:
Robert Small 1.9
Students with a GPA of 3.5 or higher:
Tom Wang 3.5
When writing the highlow function, take advantage of the fact that the array elements are sorted based on the GPA, so to find all the students with a GPA of equal to or higher than the minimum GPA, it doesn't make sense to start from the first element in the array. Instead you can start from the midpoint. If the midpoint is lower than the minimum GPA, you can increment the index until the midpoint is no longer smaller and then all the GPA's from that point on will be larger and part of the high GPA's. For low GPA's of course, you'd want to start from the beginning of the array and compare and store each that's lower than the maximum until they are no longer lower.
Functions you must write for this assignment (in addition to main):
initialize, read, display, sort_name, sort_gpa, search-name, search_gpa, stats, highlow.
Upload your cpp and exe files using the Browse and Upload buttons below and click Finish once both have been uploaded to the site.*/
I debugged it for you.
The problem is in your stringToCharArray(string s, char c[]).
My index i arrived to 104 before getting "segmentation fault". Since all your strings have length 50 you are clearly going out of bounds.
Another problem is in srtstr that returns NULL, but this is related to the first problem.
A quick look to your sort_name and InsertItem didn't show up anything wrong, at least in the field of "segmentation error", since it's not so clear what you are trying to do, but at least you are performing the right index checks.

Need help in basic C++ regarding how to properly loop through part and finding smallest value

Hi I'm needing some help. I'm in a intro to programming class and we are using c++. I am hoping someone can help me with an assignment that was due yesterday (I understand not to expect miracle responses but a girl can always try).
I'm having two problems that I know of. The first is regarding the smallest value.
The big one is in trying to make it loop for requirements of three times but not lose out on my total count. I cannot use arrays or anything I haven't learned yet which is why I've posted this. I've seen similar problems and questions but they have ended up with answers too complex for current progress in class. So here is the problems instructions:
Instructions
1) Write a program to find the average value, the largest value, and the smallest value of a set of numbers supplied as input from the keyboard. The number of values in the data set must be in the range 0 to 20, inclusive. The user will first enter the number of values in the data set(use variable int Number). Give the user 3 attempts at entering Number in the range given. If the value for Number entered is out of this range, write an error message but continue. If the user does not enter a valid value for Number within the 3 attempts print an error message and terminate the program.
2) Format only the output for the Average value to 3 decimal places when printed.
3) The values in the data set entered as input can be any value positive, negative, or zero.
4) Make the program output readable(see the example below). (Note: that you will notprint out the input values that were entered in this program like you normally are required to do. This is because we have not covered the “tool” needed to do so yet in our studies).
Below will be the output from the execution of your program:
(using these values in order for the data set --> 19.0 53.4 704.0 -15.2 0 100.0)
The largest number: 704
The smallest number: -15.2
The average of the 6 numbers entered: 143.533
yourName L4p2XX.cpp
Lab#4 prob 2 XX-XX-12
Here is my poor excuse at the solution:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double Number = 0, minValue, maxValue, average, total = 0;
int ct = 0, numCount;
cout << "How many numbers would you like to enter? ";
cin >> numCount;
for(ct = 1; ct <= numCount; ct += 1)
{
cout << "Enter Value from 0 to 20, inclusive: ";
cin >> Number;
if(Number > 20|| Number < 0)
for(int errorCt = 1; errorCt <= 4; errorCt += 1)
{
if(errorCt == 4)
{
cout << "You have had 3 attempts to enter a valid" <<
"number. \nPlease try this program again when you" <<
"are able to follow directions.";
cout <<"\nLBn\n"<<"L4P2LB.cpp\n"<<"11-05-12\n";
return 0;
}
cout << Number << "is not within range.\n" <<
"Please enter a number from 0 to 20: ";
cin >> Number;
} //end for loop
total += Number;
if(maxValue <= Number)
maxValue = Number;
if(Number <= minValue)
minValue = Number;
} //end for loop
cout << "The smallest number entered was " << minValue << endl;
cout << "The largest number you entered was " << maxValue << endl;
average = total/numCount;
cout << setprecision(3) << fixed << showpoint << "You entered " <<
numCount << " numbers. The average of these is " << average;
//Program ID
cout <<"\n" << "L4P2LB.cpp\n" << "11-05-12\n";
system ("pause");
return 0;
} // End main
Thank you in advance to anyone who can steer me in the right direction. Not looking for anyone to do my work I just need help in direction if nothing else or any suggestions as to what to do. Thanks again. Lynda
Also I need somehow to pause after the third time and exit properly. If I put the second pause in it won't work so am I missing something obvious there too!
The first problem I see is that you didn't initialize a couple of variables.
You should either initialize both minValue and maxValue variables with something which will overwritten in every case in the first loop (typically "positive/negative infinity", as provided by <limits>), or just set both to Number in the first iteration, regardless of their current value. So I'd suggest to fix this by replacing
if(maxValue <= Number)
maxValue = Number;
if(Number <= minValue)
minValue = Number;
with
if(maxValue <= Number || ct == 1)
maxValue = Number;
if(Number <= minValue || ct == 1)
minValue = Number;
as ct == 1 will be true in the first iteration.
That said, you check the 0..20 range condition on the wrong variable. You check it on the Number variable, but you should check the numCount variable. But you also didn't respect the requirement that the variable to store the "number of numbers" should be Number, so you did check the correct variable, but used the wrong to read the input into. This should fix this issue (I changed the variable name in the cin >>... line + moved the check outside your main loop):
cout << "How many numbers would you like to enter? ";
cin >> Number;
if(Number > 20|| Number < 0)
{
for(int errorCt = 1; errorCt <= 4; errorCt += 1)
...
if(errorCt == 4)
{
cout << "You have had 3 attempts to enter a valid" <<
"number. \nPlease try this program again when you" <<
"are able to follow directions.";
cout <<"\nLBn\n"<<"L4P2LB.cpp\n"<<"11-05-12\n";
return 0;
}
cout << Number << "is not within range.\n" <<
"Please enter a number from 0 to 20: ";
cin >> Number;
} //end for loop
}
for(ct = 1; ct <= Number; ct += 1)
{
...
}
...

string input help from keyboard emulator

I have wrote some basic code for a project. I am at the point I am trying to take an input from a RFID reader using a keyboard emulator. The follwing is my code to this point:
#include <iostream>
#include <ios>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
char product; //declaring the variable for the switch/case
int Pay = 0; //Declaring the variable Pay
int Payment = 0;
double Total = 0; // Declaring the Final Total variable
double Subtotal = 0; // Declaring the variable Subtotal
double Tax = 0; // Declaring the variable Tax
int m = 0; //counts the amount of times milk is scanned
int b = 0; //counts the amount of times beer is scanned
int c = 0; //counts the amount of times candy bar is scanned
int r = 0; //counts the amount of times rice is scanned
cout << "Scan the product you desire to purchase: \n";//Asking user to input product purchasing
cout << "When ready to checkout press the z button.\n\n\n"; //Telling user to press button z to pay
while(Pay < 1) //Keeps in the loop until pay is increased to 1
{
getline(cin, product); //Taking input and assining to the variable product
if(product == E007C02A55EF918D)
{
cout << "6 pack of Budlight...........$6.49\n"; // If the button b is pushed displays
Subtotal = Subtotal + Beer; // Calculates the Subtotal and stores it
Tax = Beer * Taxrate + Tax; // Claculates the total Tax and stores it
b++;
}
else if(product == E007C02A55EF937C)
{
cout << "Snickers Bar.................$0.99\n";// If the button c is pusehd displays
Subtotal = Subtotal + Candy_Bar;
Tax = Candy_Bar * Taxrate + Tax;
c++;
}
else if(product == E007C02A554A7A8B)
{
cout << "1 Gallon of 2% Milk..........$3.99\n";//If the button m is pushed displays
Subtotal = Subtotal + Milk;
m++;
}
else if(product == E007C02A55CE0766)
{
cout << "Box of Brown Rice............$2.79\n";//If the button r is pushed displays
Subtotal = Subtotal + Rice;
r++;
}
else
cout << "Invaild product. Please scan a different product.\n";
if (product == 'z')
Pay++; //When finished it increases pay to 1 to break the while loop
Total = Subtotal + Tax; // Claculates the Total
}
I am using MSVS 2010 to compile this code. With this code I can not compile because it says E007C02A55EF918D is undefined. E007C02A55EF918D is the serial number from one of the RFID tags and is what I am trying to input. I know I am having problems with the getline function also, but I am more worried about getting the serial number as an input.
char is big enough for a single character (it is usually an 8bit quantity, but don't rely on that).
So your product variable can only hold one char.
E007C02A55EF918D is an identifier (because it begins with a letter, it is not considered as a number, and because it is not quoted, it is not interpreted as a string).
If you intended product and those serial numbers to be 64bit numbers, you'll need to change product to be large enough to store them (uint64_t for instance), and change the serial numbers in your code to be numbers by prefixing with 0x. You'll also have to change your input method (getline takes strings, so you will need to convert that string to a number - see How to convert a number to string and vice versa in C++ for instance).
if (product == 0xABCD1234)
If you indented both to be strings, then declare product with:
std::string product;
and quote ("") the serial numbers. You'll also need to change the last test to:
if (product == "z")
^ ^
You can't compare an std::string with a single char ('z' is a char, "z" is a C-style 0-terminated string).
Try having it in "" and use strcmp() instead of ==, like
if (!strcmp("E007C02A55EF937C",product))
or
if (strcmp("E007C02A55EF937C",product)==0)
Hope it helped you.