for loop character printing [closed] - c++

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
.....................HEY GUYS,I GOT THE ANSWER.PLEASE CHECK OUT AT BOTTOM.....................
ThAnKs FoR aLl ThOsE wHo TrYiNg tO hElP mE!
How to print all the character outside the for-loop that input inside for-loop? It only prints the last character entered in for-loop
input all 4 names of items and price in void shop::getdata()
output of this only prints the name of item that entered last in void shop::getdata() for 4 times in void shop::putdata()
output of price is correct,it prints orderly.
what's the problem with the name of item?
Question:WAP to store pricelist of 5 items & print the largest price as well as the sum of all prices & pricelist also.
#include<iostream.h>
#include<conio.h>
#include<string.h>
class shop
{
int i;
char item[50];
float price[50];
public:
void getdata();
void putdata();
float sum();
float lar();
};
void shop::getdata()
{
for(i = 0; i <= 4; i++)
{
cout << "Enter the item name:" << "\n";
cin >> item;
cout << "Enter price:" << "\n";
cin >> price[i];
}
}
void shop::putdata()
{
cout << "\t\tPRICE LIST" << "\n";
cout << "\t\t**********" << "\n";
cout << "ITEM NAME\t\t\tPRICE" << "\n";
cout << "*********\t\t\t*****" << "\n";
for(i = 0; i <= 4; i++)
{
cout << item << "\t\t\t\t";
cout << price[i] << "\n";
}
}
float shop::sum()
{
float sum = 0;
for( i= 0; i <= 4; i++)
{
sum = sum + price[i];
}
cout << "\t\t\t\tsum is:" << sum << "\n";
return sum;
}
float shop::lar()
{
float lar;
lar = price[0];
for(i = 0; i <= 4; i++)
{
if (price[i] > lar)
lar = price[i];
}
cout << "\t\t\tlargest is:" << lar;
return lar;
}
void main()
{
shop x;
int c;
clrscr();
x.getdata();
do
{
cout << "\n\n1.PRICE LIST\n";
cout << "2.SUM\n";
cout << "3.LARGEST\n";
cout << "4.EXIT\n";
cout << "Enter your choice\n";
cin >> c;
switch (c)
{
case 1:
x.putdata();
break;
case 2:
x.sum();
break;
case 3:
x.lar();
break;
default:
cout << "PRESS ANY KEY TO EXIT\n";
break;
}
}
while(c >= 1 && c <= 3);
getch();
}
ANSWER
#include<iostream.h>
#include<conio.h>
#include<string.h>
class shop
{
int i;
char item[50];
float price;
float e[10];
public:
void getdata();
void putdata();
float sum();
float lar();
};
void shop::getdata()
{
cout << "Enter the item name:" << "\n";
cin >> item;
cout << "Enter price:" << "\n";
cin >> price;
}
void shop::putdata()
{
cout << item << "\t\t\t\t";
cout << price << "\n";
}
float shop::sum()
{
float sum = 0;
for( i= 0; i <= 4; i++)
{
cout<<"Enter prices"<<"\n";
cin>>e[i];
sum = sum + e[i];
}
cout << "\t\t\t\tsum is:" << sum << "\n";
return sum;
}
float shop::lar()
{
float lar;
lar = e[0];
for(i = 0; i <= 4; i++)
{
if (e[i] > lar)
lar = e[i];
}
cout << "\t\t\tlargest is:" << lar;
return lar;
}
void main()
{
shop x[10];
int c,i;
clrscr();
for(i=0;i<=4;i++)
x[i].getdata();
do
{
cout << "\n\n1.PRICE LIST\n";
cout << "2.SUM\n";
cout << "3.LARGEST\n";
cout << "4.EXIT\n";
cout << "Enter your choice\n";
cin >> c;
switch (c)
{
case 1:
for(i=0;i<=4;i++)
x[i].putdata();
break;
case 2:
x[i].sum();
break;
case 3:
x[i].lar();
break;
default:
cout << "PRESS ANY KEY TO EXIT\n";
break;
}
}
while(c >= 1 && c <= 3);
getch();
}

It's a little hard to tell what you're asking (you would do well to indent your code and ask a clearer question), but I think your problem (well, the main one you're referring to!) is how you're handling item names.
You've declared your shop to contain an array of 50 chars - that is, 50 single characters. Since you have an array of 50 prices, you almost certainly wanted an array of 50 strings. In basic C, that would be char *item[50], an array of 50 dynamically-allocated char arrays. Since you've tagged this as C++, though, you're better off using a string.

A slightly more modern shop would look like this:
#include <iostream>
#include <string>
#include <vector>
using std::cin;
using std::cout;
using std::ostream;
using std::string;
using std::vector;
class Item {
string m_name;
double m_price;
public:
Item(const string &name, double price)
: m_name(name), m_price(price) {
};
string name() const { return m_name; }
double price() const { return m_price; }
};
class Shop {
vector<Item> m_items;
public:
void readData();
void writeData() const;
double getPriceSum() const;
double getMaxPrice() const;
};
void Shop::readData() {
for (;;) {
string name, end_of_line;
double price;
cout << "Enter the item name (or nothing to finish input): ";
getline(cin, name);
if (name == "") {
break;
}
cout << "Enter the price: ";
cin >> price;
// the previous ">>" left the end-of-line in the stream,
// so read it now.
getline(cin, end_of_line);
m_items.push_back(Item(name, price));
}
}
void Shop::writeData() const {
for (size_t i = 0; i < m_items.size(); i++) {
const Item &item = m_items[i];
cout << item.name() << "\t" << item.price() << "\n";
}
}
double Shop::getPriceSum() const {
double sum = 0.0;
for (size_t i = 0; i < m_items.size(); i++) {
sum += m_items[i].price();
}
return sum;
}
double Shop::getMaxPrice() const {
double max = 0.0; // assume that all prices are positive
for (size_t i = 0; i < m_items.size(); i++) {
max = std::max(max, m_items[i].price());
}
return max;
}
int main() {
Shop shop;
shop.readData();
shop.writeData();
cout << "sum: " << shop.getPriceSum() << "\n";
cout << "max: " << shop.getMaxPrice() << "\n";
return 0;
}
It is not perfect C++ style, but still makes the code easy to read.

Related

C++ undefined reference to `findGrossPay(employeeInfo, double, int)'

A class I've been working on for a few days, running into an error I'm unsure how to fix.
#include <iostream> // for cin, cout, endl
#include <string>
#include <iomanip> // formatting floats
using namespace std;
void programHeader();
void footer();
void printEmployeeInfo(struct employeeInfo);
struct employeeInfo
{
int employeeID;
char employeeName[20];
double payRate;
int employeeType;
};
float findGrossPay(employeeInfo myEmployee, double , int);
void payrollDisplay(employeeInfo myEmployee, double, double, double, float, float);
//prototype declerations
int main()
{
// decleration of variables
float inputNumber1;
int num1;
int num2;
int num3;
int num4;
employeeInfo myEmployee[4];
float totalGross;
float totalNet;
int maxName = 20;
int location;
double hoursArray[4];
double grossPay[4];
double tax[4];
double netPay[4];
// input section
programHeader();
num4 = 0;
location = 0;
for (int c = 0; c < 4; c++) // fill in the array of structs
{
while (true); // validation loop
{
cout << "Employee ID: ";
cin >> num1;
if (num1 > 0);
{
myEmployee[c].employeeID = num1;
break;
} // end if
if (num1 <= 0)
{
cout << "\nERROR PLEASE TRY AGAIN" << endl;
} // end else if
} // end while
cout << "Employee Name: ";
cin.getline(myEmployee[c].employeeName, maxName);
while (true); // validation loop
{
cout << "Pay rate: ";
cin >> num2;
if (num2 > 0);
{
myEmployee[c].payRate = num2;
break;
} // end if
if (num2 <= 0)
{
cout << "\nERROR PLEASE TRY AGAIN" << endl;
} // end if
} // end while
while (true) // validation loop
{
cout << "Type: ";
cin >> num3;
if ((num3 == 1) || (num3 == 0))
{
myEmployee[c].employeeType = num3;
break;
} // end if
else
{
cout << "\nERROR PLEASE TRY AGAIN" << endl;
} // end else
} // end while
} // end for(c)
for (int h = 0; h < 4; h++); // parallel array to hold hours worked
{
cout << "Hours worked for " << myEmployee[num4].employeeName << ": ";
cin >> hoursArray[num4];
num4 = num4 +1;
} // end for(h)
// calculation section
// displays the results
for (int l = 0; l < 4; l++) // l for location
{
grossPay[l] = findGrossPay(myEmployee[4], hoursArray[4], location);
location = location + 1;
} // end for(l)
for (int t = 0; t < 4; t++) // get taxes and net pay for each
{
tax[t] = grossPay[t] * (15 / 100);
netPay[t] = grossPay[t] - tax[t];
}
for (int i = 0; i < 4; i++)
{
totalGross = totalGross + grossPay[i];
totalNet = totalNet + netPay[i];
} // end of for
payrollDisplay(myEmployee[4], grossPay[4], tax[4], netPay[4], totalGross, totalNet);
footer();
system("PAUSE");
return 0;
}// end of main
float findGrossPay(employeeInfo myEmployee[4], double hoursArray[4], int l) // l stands for location
{
float numGrossPay;
if (myEmployee[l].employeeType == 1) // management
{
numGrossPay = myEmployee[l].payRate * hoursArray[l];
} // end if
else if (myEmployee[l].employeeType == 0) // union members
{
if (hoursArray[l] > 40)
{
numGrossPay = myEmployee[l].payRate * 40 + (hoursArray[l] - 40) * (myEmployee[l].payRate * 1.5);
} // end if
else
{
numGrossPay = myEmployee[l].payRate * hoursArray[l];
} // end else
} // end else if
return numGrossPay;
}
void payrollDisplay(employeeInfo myEmployee[4], double grossPay[4], double tax[4], double netPay[4], float totalGross, float totalNet)
{
cout << "------------------------------------------------------------" << endl;
cout << "\nPayroll Report\n" << endl;
cout << "ID \tName" << "\t\tGross Pay \tTax \tNet Pay" << endl;
for (int i = 0; i < 4; i++) // to print each employee
{
cout << myEmployee[i].employeeID << "\t" << myEmployee[i].employeeName << "\t\t" << grossPay[i]
<< "\t" << tax[i] << "\t" << netPay[i] << endl;
} // for(i)
cout << "\nTotal Gross Pay \t$" << totalGross << endl;
cout << "Total Net Pay \t$" << totalNet << endl;
}
It's giving me an error stating there is an undefined reference to these lines in main():
grossPay[l] = findGrossPay(myEmployee[4], hoursArray[4], location);
and
payrollDisplay(myEmployee[4], grossPay[4], tax[4], netPay[4], totalGross, totalNet);
The "undefined reference" errors are because your function declarations do not match their definitions.
You have declared findGrossPay() and payrollDisplay() as taking in a single employeeInfo and related values for that one employee, but then your definitions are taking in arrays of employees and values:
//declaration
float findGrossPay(employeeInfo myEmployee, double , int);
//definition
float findGrossPay(employeeInfo myEmployee[4], double hoursArray[4], int l)
// declaration
void payrollDisplay(employeeInfo myEmployee, double, double, double, float, float);
//definition
void payrollDisplay(employeeInfo myEmployee[4], double grossPay[4], double tax[4], double netPay[4], float totalGross, float totalNet)
As such, the linker can't find matching definitions for the functions you are actually calling.
And, to make that worse, the places where you are calling these functions are accessing array elements out of bounds, which is undefined behavior.
After you fix that problem, you should then get "undefined reference" errors for programHeader() and footer(), since their definitions are missing completely.
After fixing that, there are still other problems with your code:
you have a number of if and for/while loops that have an erroneous ; on them
you are accessing arrays incorrectly in some places
you have uninitialized variables in some of your calculations
With that said, try something more like this:
#include <iostream> // for cin, cout, endl
#include <string>
#include <iomanip> // formatting floats
#include <limits>
using namespace std;
struct employeeInfo
{
int employeeID;
string employeeName;
double payRate;
int employeeType;
};
//prototype declerations
void programHeader();
void footer();
int promptForNumber(const string &prompt, int minValue = 0, int maxValue = numeric_limits<int>::max());
string promptForString(const string &prompt);
float findGrossPay(const employeeInfo &myEmployee, double hours);
void payrollDisplay(const employeeInfo myEmployee[4], const double grossPay[4], const double tax[4], const double netPay[4]);
int main()
{
// decleration of variables
employeeInfo myEmployee[4];
double hours[4];
double grossPay[4];
double tax[4];
double netPay[4];
int num;
// input section
programHeader();
for (int c = 0; c < 4; c++) // fill in the array of structs
{
myEmployee[c].employeeID = promptForNumber("Employee ID", 1);
myEmployee[c].employeeName = promptForString("Employee Name");
myEmployee[c].payRate = promptForNumber("Pay rate", 1);
myEmployee[c].employeeType = promptForNumber("Type", 0, 1);
}
for (int h = 0; h < 4; h++) // parallel array to hold hours worked
{
hours[h] = promptForNumber("Hours worked for " << myEmployee[h].employeeName);
}
// calculation section
for (int l = 0; l < 4; l++) // l for location
{
grossPay[l] = findGrossPay(myEmployee[l], hours[l]);
}
for (int t = 0; t < 4; t++) // get taxes and net pay for each
{
tax[t] = grossPay[t] * (15 / 100);
netPay[t] = grossPay[t] - tax[t];
}
// displays the results
payrollDisplay(myEmployee, grossPay, tax, netPay);
footer();
system("PAUSE");
return 0;
}
void programHeader()
{
// print out something here...
}
void footer()
{
// print out something here...
}
int promptForNumber(const string &prompt, int minValue, int maxValue)
{
int num;
while (true) // validation loop
{
cout << prompt << ": ";
if (cin >> num)
{
cin.ignore(numeric_limits<streamsize>::max(), '\n');
if ((num >= minValue && num <= maxValue)
break;
}
else
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
cout << "\nERROR PLEASE TRY AGAIN" << endl;
}
return num;
}
string promptForString(const string &prompt)
{
string input;
while (true) // validation loop
{
cout << prompt << ": ";
if (getline(cin, input) && !input.empty())
break;
cout << "\nERROR PLEASE TRY AGAIN" << endl;
}
return input;
}
float findGrossPay(const employeeInfo &myEmployee, double hours)
{
if (myEmployee.employeeType == 1) // management
{
return myEmployee.payRate * hours;
}
// must be myEmployee.employeeType == 0 // union members
if (hours > 40)
{
return myEmployee.payRate * 40 + (hours - 40) * (myEmployee.payRate * 1.5);
}
else
{
return myEmployee.payRate * hours;
}
}
void payrollDisplay(const employeeInfo myEmployee[4], const double grossPay[4], const double tax[4], const double netPay[4])
{
float totalGross = 0.0f;
float totalNet = 0.0f;
cout << "------------------------------------------------------------" << endl;
cout << "\nPayroll Report\n" << endl;
cout << "ID \tName" << "\t\tGross Pay \tTax \tNet Pay" << endl;
for (int i = 0; i < 4; i++) // to print each employee
{
cout << myEmployee[i].employeeID << "\t" << myEmployee[i].employeeName << "\t\t" << grossPay[i] << "\t" << tax[i] << "\t" << netPay[i] << endl;
totalGross += grossPay[i];
totalNet += netPay[i];
}
cout << "\nTotal Gross Pay \t$" << totalGross << endl;
cout << "Total Net Pay \t$" << totalNet << endl;
}
That said, you might consider moving the hours/grossPay/tax/netPay values into the employeeInfo struct, so that you have to manage only 1 array and not 5 parallel arrays.

Array search and unique value addition

(Sorry if this is formatted terribly. I've never posted before.)
I've been working on a program for class for a few hours and I can't figure out what I need to do to my function to get it to do what I want. The end result should be that addUnique will add unique inputs to a list of its own.
#include <iostream>
using namespace std;
void addUnique(int a[], int u[], int count, int &uCount);
void printInitial(int a[], int count);
void printUnique(int u[], int uCount);
int main() {
//initial input
int a[25];
//unique input
int u[25];
//initial count
int count = 0;
//unique count
int uCount = 0;
//user input
int input;
cout << "Number Reader" << endl;
cout << "Reads back the numbers you enter and tells you the unique entries" << endl;
cout << "Enter 25 positive numbers. Enter '-1' to stop." << endl;
cout << "-------------" << endl;
do {
cout << "Please enter a positive number: ";
cin >> input;
if (input != -1) {
a[count++] = input;
addUnique(a, u, count, uCount);
}
} while (input != -1 && count < 25);
printInitial(a, count);
printUnique(u, uCount);
cout << "You entered " << count << " numbers, " << uCount << " unique." << endl;
cout << "Have a nice day!" << endl;
}
void addUnique(int a[], int u[], int count, int &uCount) {
int index = 0;
for (int i = 0; i < count; i++) {
while (index < count) {
if (u[uCount] != a[i]) {
u[uCount++] = a[i];
}
index++;
}
}
}
void printInitial(int a[], int count) {
int lastNumber = a[count - 1];
cout << "The numbers you entered are: ";
for (int i = 0; i < count - 1; i++) {
cout << a[i] << ", ";
}
cout << lastNumber << "." << endl;
}
void printUnique(int u[], int uCount) {
int lastNumber = u[uCount - 1];
cout << "The unique numbers are: ";
for (int i = 0; i < uCount - 1; i++) {
cout << u[i] << ", ";
}
cout << lastNumber << "." << endl;
}
The problem is my addUnique function. I've written it before as a for loop that looks like this:
for (int i = 0; i < count; i++){
if (u[i] != a[i]{
u[i] = a[i]
uCount++;
}
}
I get why this doesn't work: u is an empty array so comparing a and u at the same spot will always result in the addition of the value at i to u. What I need, is for this function to scan all of a before deciding whether or no it is a unique value that should be added to u.
If someone could point me in the right direction, it would be much appreciated.
Your check for uniqueness is wrong... As is your defintion of addUnique.
void addUnique(int value, int u[], int &uCount)
{
for (int i = 0; i < uCount; i++){
if (u[i] == value)
return; // already there, nothing to do.
}
u[uCount++] = value;
}

Can't find a solution to a c++ program [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
So I have to write a code for the following program:
Write a program with a main function and menu for choosing a function to:
a) input data for students into an array (faculty number, age, sex) (up to 25)
b) rewrite the data for the male and female students into two new arrays and output the arrays and the average age
c) output the youngest student and make the arrays into ascending order of the age and output the arrays
d) search for a student by a faculty number and output his information
Ok, so far so good. The a) and d) are working as they should, but b) and c) are giving me some trouble. On c) it says the youngest student is -88758375 year-old and it isn't outputting the arrays. And on b) it gives me a logical error and it says Integer division by zero and crashes the program. I really tried to find any mistakes but I'm stuck, so I ask you for some help:)))
#include "stdafx.h"
#include <iostream>
using namespace std;
const int N = 25;
struct student
{
int fN;
int age;
char sex;
};
// a)
void input(student fN[N], int numberOfStudents)
{
for (int i = 0; i<numberOfStudents; i++)
{
cout << "Faculty number: ";
cin >> fN[i].fN;
cout << "Age: ";
cin >> fN[i].age;
cout << "Sex: ";
cin >> fN[i].sex;
cout << endl;
}
}
// b)
void rearrange(student fN[N], student fNm[N], student fNf[N], int numberOfStudents, int m, int f)
{
int avgAgeM = 0, avgAgeF = 0;
for (int i = 0; i < numberOfStudents; i++)
{
if (fN[i].sex == 'm')
{
fNm[m].fN = fN[i].fN;
fNm[m].age = fN[i].age;
fNm[m].sex = fN[i].sex;
m++;
avgAgeM = avgAgeM + fN[i].age;
}
else if (fN[i].sex == 'f')
{
fNf[f].fN = fN[i].fN;
fNf[f].age = fN[i].age;
fNf[f].sex = fN[i].sex;
f++;
avgAgeF = avgAgeF + fN[i].age;
}
cout << endl;
for (int i = 0; i < m; i++)
{
cout << "\tFaculty number: " << fNm[i].fN << "\tAge: " << fNm[i].age << "\tSex: " << fNm[i].sex << endl;
}
cout << "Average male age: " << avgAgeM / m << "\n\n";
for (int i = 0; i<f; i++)
{
cout << "\tFaculty number: " << fNf[i].fN << "\tAge: " << fNf[i].age << "\tSex: " << fNf[i].sex << endl;
}
cout << "Average female age: " << avgAgeF / f << "\n\n";
}
}
// c)
void ascendingAge(student fNm[N], student fNf[N], int m, int f)
{
int x, y;
char z;
for (int i = 0; i < m-1; i++)
for (int j = 0; j < m-i-1; j++)
{
if (fNm[j].age > fNm[j + 1].age)
{
x = fNm[j].age;
y = fNm[j].fN;
z = fNm[j].sex;
fNm[j + 1].age = fNm[j].age;
fNm[j].age = x;
fNm[j + 1].fN = fNm[j].fN;
fNm[j].fN = y;
fNm[j + 1].sex = fNm[j].sex;
fNm[j].sex = z;
}
}
for (int i = 0; i < f-1; i++)
for (int j = 0; j < f-i-1; j++)
{
if (fNf[j].age > fNf[j + 1].age)
{
x = fNf[j].age;
y = fNf[j].fN;
z = fNf[j].sex;
fNf[j + 1].age = fNf[j].age;
fNf[j].age = x;
fNf[j + 1].fN = fNf[j].fN;
fNf[j].fN = y;
fNf[j + 1].sex = fNf[j].sex;
fNf[j].sex = z;
}
}
cout << "The youngest female student is " << fNf[0].age << " year-old." << endl;
for (int i = 0; i < m; i++)
cout << "\tFaculty number: " << fNm[i].fN << "\tAge: " << fNm[i].age << "\tSex: " << fNm[i].sex << endl;
for (int i = 0; i<f; i++)
cout << "\tFaculty number: " << fNf[i].fN << "\tAge: " << fNf[i].age << "\tSex: " << fNf[i].sex << endl;
cout << endl;
}
//d
void searchStudent(student fN[N], int numberOfStudents)
{
int x, index;
bool yes = false;
cout << "Enter a faculty number: ";
cin >> x;
for (int i = 0; i < numberOfStudents; i++)
if (fN[i].fN == x)
{
yes = true;
index = i;
}
cout << endl;
if (yes == true)
cout << "\tFaculty number: " << fN[index].fN << "\tAge: " << fN[index].age << "\tSex: " << fN[index].sex << endl;
else
cout << "No such faculty number.\n\n";
}
int main()
{
student fN[N], fNm[N], fNf[N];
int numberOfStudents, m = 0, f = 0;
char check;
cout << "Enter number of students: ";
cin >> numberOfStudents;
BACK:
cout << "\n\n";
cout << "\t a) \n\t b) \n\t c) \n\t d)\n Press'q' to exit.\n\n";
cin >> check;
switch (check)
{
case 'a':
input(fN, numberOfStudents);
goto BACK;
break;
case 'b':
rearrange(fN, fNm, fNf, numberOfStudents, m, f);
goto BACK;
break;
case 'c':
ascendingAge(fNm, fNf, m, f);
goto BACK;
break;
case 'd':
searchStudent(fN, numberOfStudents);
goto BACK;
break;
case 'q':
return 0;
break;
default:
cout << "Wrong input.\n";
goto BACK;
}
system("pause");
return 0;
}
In the function rearrange you need pass m and k by reference:
void rearrange(student fN[N], student fNm[N], student fNf[N], int numberOfStudents, int& m, int& f):
Оr they will not be changed
You seem to want m and f to be outputs from this function
void rearrange(student fN[N], student fNm[N], student fNf[N], int numberOfStudents, int m, int f)
but that would work only if passed by reference:
void rearrange(student fN[N], student fNm[N], student fNf[N], int numberOfStudents, int& m, int& f)
You should guard against divide by zero by testing. Instead of:
cout << "Average male age: " << avgAgeM / m << "\n\n";
use
if (m)
cout << "Average male age: " << avgAgeM / m << "\n\n";
else
cout << "There are zero males\n\n";
and similarly for f

setPercent function is printing garbage data [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Just started working with OOP and it hasnt been very fun. im writing a program where the user chooses 3options from a menu (1. print all 2. change score 3. quit) Im stuck on the print all function. I want to print out 3 things the name of each student their percent and their scores(the scores and names are read in from a file). Problem is percent keeps printing out garbage data. So i did some debugging and i found out that when i read in the scores of each student its reading in extra values of garbage data which is ruining the calculation. I've tried to fix it but havent had any luck. All help and tips are appreciated below is the code and i will also post the IMG of my debugging and the garbage data i found being stored in scores[i].
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
using namespace std;
class Student
{
private:
string name;
int *scores;
int numstu;
int numscores;
int maxscore;
double percent;
public:
//Mutator
void setName(string inName) {name = inName;}
void setNumstu(int iNum) {numstu = iNum;}
void setNumscores(int sNum) {numscores = sNum;}
void setMaxscore(int mNum) {maxscore = mNum;}
void setScores(int *list);
void setPercent ();
//Accessor
string getName () const {return name;}
int getNumScores () const {return numscores;}
int getNumStu () const {return numstu;}
int getMaxScore () const {return maxscore;}
double getPercent () const {return percent;}
int *getScoreslist () const {return scores;}
//constructor
//Student();
};
void Student::setScores(int *list)
{
scores = new int[numscores];
for (int i = 0; i < numscores; i++)
{
scores[i] = list[i];
}
};
void Student::setPercent()
{
double sum = 0;
//debugging shows scores is being filled with garbage data
for (int i = 0; i < numscores; i++)
{
cout << scores[i] << endl;
}
for(int i = 0; i < numscores; i++)
{
sum = sum + scores[i];
}
//cout << sum;
percent = (sum/maxscore) * 100.0;
sum = 0;
//cout << percent;
};
Student *fillArr(int &numstu, int &numscores, int &maxscore);
void printAll(Student *stuArr, int numstu, int numscores);
int main()
{
int numstu;
int numscores;
int maxscore;
int choice;
Student *stuArr;
stuArr = fillArr(numstu, numscores, maxscore);
if(stuArr == 0)
{
cout << "Error." << endl;
return 0;
}
cout << "Menu:" << endl;
cout << "1. Print All" << endl;
cout << "2. Change Score" << endl;
cout << "3. Quit" << endl;
cin >> choice;
do
{
if(choice == 1)
{
printAll(stuArr, numstu, numscores);
}
else if (choice == 2)
{
cout << "Change Score" << endl;
}
else if (choice == 3)
{
cout << "Good Bye" << endl;
exit(100);
}
else
{
cout << "That is not a valid option." << endl;
return 0;
}
} while (choice !=1 && choice !=2 && choice != 3);
return 0;
};
Student *fillArr(int &numstu, int &numscores, int &maxscore)
{
//Opening file and checking if it exists
ifstream infile;
infile.open("grades.txt");
if(!infile)
{
cout << "Error Opening file\n";
return 0;
}
string temp;
//Reding in number of students, number of scores, and maximum score
infile >> numstu >> numscores >> maxscore;
//Dynamically Allocating new memory for each student
Student *newStu = new Student[numstu];
infile.ignore();
for (int i = 0; i < numstu; i++)
{
getline(infile, temp);
newStu[i].setName(temp);
newStu[i].setMaxscore(maxscore);
newStu[i].setNumscores(numstu);
int *list = new int[numscores];
for (int z = 0; z < numscores; z++)
{
infile >> list[z];
};
newStu[i].setScores(list);
infile.ignore();
};
return newStu;
infile.close();
};
void printAll(Student *stuArr, int numstu, int numscores)
{
cout << "Name\t" << "\tGrade\t" << "\tScores\t" << endl;
for (int i = 0; i < numstu; i++)
{
//calling setpercent mutator
stuArr[i].setPercent();
cout << setprecision(1) << fixed << left;
//printing out each name and percent of each student
cout << setw(20) << stuArr[i].getName() << setw(19) << stuArr[i].getPercent() << setw(20);
printing out the scores of each student works correctly here for some odd reason
const int *ptr = stuArr[i].getScoreslist();
for (int z = 0; z < numscores; z++)
{
cout << left;
cout << setw(4) << ptr[z];
}
cout << endl;
}
};
Found the bug in this line: newStu[i].setNumscores(numstu); it should be newStu[i].setNumscores(numscores); instead

C++ Programming Errors: C4703, C4700

i am relatively new to programming, i just learned c++ and i am getting 2 errors for a HW assignment from school;
Error 2 error C4700: uninitialized local variable 'searchValueptr' used Line 83
and
Error 3 error C4703: potentially uninitialized local pointer variable 'createdArray' used
Line 70
I cannot for the life of me figure out why or how to fix it can some one help me please.
#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;
// prototypes
int *createArray(int &size);
void findStats(int *arr, int size, int &min, int &max, double &average);
int *searchElement(int *arr, int size, int *element);
int main ()
{
int choice, size;
bool menuOn = true;
while (menuOn == true)
{
cout << "1 - Create and initialize a dynamic array.\n";
cout << "2 - Display statistics on the array.\n";
cout << "3 - Search for an element.\n";
cout << "4 - Exit.\n";
cout << "Enter your choice and press return: ";
cin >> choice;
cout << endl;
switch (choice)
{
case 1:
int *createdArray;
cout << "Please enter a size for the array: ";
cin >> size;
createdArray = createArray(size);
for (int x=0; x < size; x++)
{
cout << "Value of array at index " << x << ": " << createdArray[x] << endl;
}
cout << endl;
break;
case 2:
int minNum;
int maxNum;
double avgNum;
findStats(createdArray, size, minNum, maxNum, avgNum);
cout << endl << "The maximum number is: " << maxNum;
cout << endl << "The minimum number is: " << minNum;
cout << endl << "The average number is: " << avgNum;
cout << endl << endl;
break;
case 3:
int *searchValueptr;
int searchValue;
cout << "Enter a value to search for: ";
cin >> searchValue;
*searchValueptr = searchValue;
searchElement(createdArray, size, searchValueptr);
break;
case 4:
cout << "Thanks for using this program";
menuOn = false;
break;
default:
cout << "Not a Valid Choice. \n";
cout << "Choose again.\n";
cin >> choice;
break;
}
}
cout << endl;
system("pause");
return 0;
} // end function main ()
int *createArray(int &size)
{
unsigned seed = time(0);
srand(seed);
int *randArray = new int [size];
for (int x=0; x < size; x++)
{
randArray[x] = rand();
}
cout << endl;
return randArray;
}
void findStats(int *arr, int size, int &min, int &max, double &average)
{
min = arr[0];
max = arr[0];
double sum = 0;
for (int count = 0; count < size; count++)
{
if (min >= arr[count])
{
min = arr[count];
}
if (max <= arr[count])
{
max = arr[count];
}
sum += arr[count];
}
average = sum/size;
}
int *searchElement(int *arr, int size, int *element)
{
bool match = false;
for (int count = 0; count < size; count++)
{
if (arr[count] == *element)
{
match = true;
}
}
if (match)
{
cout << "Match Found at: " << element;
return element;
}
else
{
cout << "No Found";
return 0;
}
}
either use
searchValueptr = &searchValue;
or send the pass the address of searchValue
searchElement(createdArray, size, &searchValue);
break;