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

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

Related

C++ Two dimensional array multiplication table

I am using C++ and want to do a 2-dimensional array. 10 rows and 3 columns. First column is(1 through 10). For Second column, user enters his/her choice of a number from (1-10) resulting in a times table displaying the results as follows: In this example the user's choice is '4':
1x4=4
2x4=8
3x4=12
4x4=16
5x4=20
6x4=24
7x4=28
8x4=32
9x4=36
10x4=40
I can't get the user's input to calculate correctly when using the for loop.
Well you can try this to get that output
#include<iostream>
using namespace std;
int main()
{
int n; //To take input
int table[10][3]; // Table
cout << "Input a number: ";
cin >> n;
// Generating Output
for (int i = 0; i < 10; i++)
{
table[i][0] = i + 1;
table[i][1] = n;
table[i][2] = table[i][0] * table[i][1];
}
for (int i = 0; i < 10; i++)
{
cout << table[i][0] << " * " << table[i][1] << " = " << table[i][2]<<endl;
}
return 0;
}
Output
SOLVED: Everything seems to be working now!! Here's the code:
#include <iostream>
#include<cstdlib>
#include<iomanip>
#include <ctime>
using namespace std;
void displayTable(int table[10][3]);
bool testMe(int testTable[10][3]);
void createTables(int testTable[10][3], int ansTable[10][3], int
usersChoice);
bool AllAnswersAreTested(bool tested[10]);
void gradeMe(int testTable[10][3], int ansTable[10][3]);
void displayMenu();
int main()
{
srand(time(NULL));
int userInput = 0;
int tableChoice = 0;
int myTable[10][3] = {0};
int testTable[10][3];
int ansTable[10][3];
bool tested = false;
do
{
displayMenu(); //Display the menu of choices
cin >> userInput;
cout << endl;
switch (userInput) //Validate menu choices 1-4
{
case 1: //Display a users choice of table
displayTable(myTable);
break;
case 2: //Test user on users choice of table
cout << "What times table test would you like to take? > ";
cin >> tableChoice;
createTables(testTable, ansTable, tableChoice);
tested = testMe(testTable);
if (tested)
{
gradeMe(testTable, ansTable);
}
break;
case 3: //Display a new table of the users choice
displayTable(myTable);
break;
case 4: //Quit program menu option
cout << "Program ending.\n";
return 0;
default: //Invalid entry
cout << "You entered an invalid item number. Please enter a number from 1 to 4.\n";
cout << endl;
}
} while (userInput != 4);
return 0;
}
void displayTable(int myTable[10][3])
{
int num; //initialize local variables
//Ask the user what times table they would like to review
cout << "What times table would you like to review?" << endl;;
cout << "Please enter a value from 1 to 12 > \n";
cout << "\n";
cin >> num;
cout << endl;
for (int i = 0; i < 10; i++)
{
myTable[i][0] = i + 1;
myTable[i][1] = num;
myTable[i][2] = myTable[i][0] * myTable[i][1];
}
for (int i = 0; i < 10; i++)
{
cout << setw(3)<< myTable[i][0] << " * " << myTable[i][1] << " = " << myTable[i][2] << endl;
}
cout << endl;
}
void createTables(int testTable[10][3], int ansTable[10][3], int usersChoice)
{
for (int i = 0; i < 10; i++)
{
testTable[i][0] = i + 1;
testTable[i][1] = usersChoice;
testTable[i][2] = 0;
ansTable[i][0] = i + 1;
ansTable[i][1] = usersChoice;
ansTable[i][2] = usersChoice * (i + 1);
}
}
bool testMe(int testTable[10][3])
{
bool tested[10] = { false, false, false, false, false,false, false, false, false, false };
while (!AllAnswersAreTested(tested))
{
int index = rand() % 10;
if (tested[index] == false)
{
int randomNum = testTable[index][0];
int tableChoice = testTable[index][1];
int answer;
cout << "What is " << randomNum << " X " << tableChoice << " = ";
cin >> answer;
testTable[index][2] = answer;
tested[index] = true;
}
}
return true;
}
bool AllAnswersAreTested(bool tested[10])
{
for (int i = 0; i < 10; i++)
{
if (tested[i] == false)
{
return false;
}
}
return true;
}
void gradeMe(int testTable[10][3], int ansTable[10][3])
{
int correctAnswers = 0;
for (int i = 0; i<10; i++)
{
if (testTable[i][2] == ansTable[i][2])
{
correctAnswers++;
}
}
int score = (correctAnswers * 10);
if (score == 100)
{
cout << "You passed the test! PERFECT SCORE!!" << endl;
cout << endl;
}
else if (score >= 70)
{
cout << "You passed the test. Your Score is: ";
cout << score;
cout << endl;
}
else if (score < 70)
{
cout << "You did not pass the test. Your Score is: ";
cout << score;
cout << endl;
}
}
//Display the menu function
void displayMenu()
{
cout << " Multiplication Tables" << endl;
cout << endl;
cout << " 1. Review MyTable" << endl;
cout << " 2. Test Me" << endl;
cout << " 3. Enter a New Multiplication Table (1-12)";
cout << " 4. Quit" << endl;
cout << " Enter a Menu Item > ";
}
#include <iostream>
using namespace std;
int main()
{
int a[100][100];
for(int i=1;i<10;i++){
for(int j=1;j<10;j++){
a[i][j] = (i)*(j);
cout<<a[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
There is how the output looks like:

Compare Class Object using bubble sort

Task: Model in OOP a class named Student containing name, surname and the marks from the winter session exams. Display the name of the students who have arrears exams and the first three students in the group.
I have troubles in comparing the marks(first three students).
My code:
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
#include <string>
#include<stdio.h>
class Student {
private:
char nume[10];
char prenume[20];
double matematica;
double fizica;
double programare;
public:
Student(char num[10], char pren[20], double mate, double fiz, double progra);
void afis();
void citire_stud();
int restanta();
double media();
};
Student::Student(char num[10] = "", char pren[20] = "", double mate = 0, double fiz = 0, double progra = 0)
{
strcpy(nume, num);
strcpy(prenume, pren);
matematica = mate;
fizica = fiz;
programare = progra;
}
void Student::afis()
{
cout << "Nume: " << nume << endl;
cout << "Prenume: " << prenume << endl;
cout << "Nota la matematica: " << matematica << endl;
cout << "Nota fizica: " << fizica << endl;
cout << "Nota programare: " << programare << endl;
cout << endl;
}
void Student::citire_stud()
{
char num[10];
char pren[20];
double mate, fiz, progra;
cout << "Introduceti numele studentului: " << endl;
cin >> num;
strcpy(nume, num);
cout << "Introduceti preumele studentului: " << endl;
cin >> pren;
strcpy(prenume, pren);
cout << "Introduceti nota la mate studentului: " << endl;
cin >> mate;
matematica = mate;
cout << "Introduceti nota la fizica studentului: " << endl;
cin >> fiz;
fizica = fiz;
cout << "Introduceti nota la programare studentului: " << endl;
cin >> progra;
programare = progra;
}
int Student::restanta() //arrears
{
if (matematica < 5 || programare <5 || fizica < 5)
return 1;
else return 0;
}
double Student::media()
{
double med;
med = (matematica + fizica + programare) / 3;
return med;
}
void main()
{
int cont = 0;
int res[10];
int nr;
cout << "Cati studenti sunt(max 10): "; //How many students
cin >> nr;
Student ob2[10], temp;
for (int i = 0;i < nr;i++)
{
ob2[i].citire_stud();
if (ob2[i].restanta())
{
res[cont++] = i;
}
}
if (cont == 0)
{
cout << "Nu sunt studenti restanti! " << endl;
goto jmp;
}
else
{
cout << "\nStundetii restanti sunt: " << endl;
int i = 0;
int k = 0;
do
{
k = res[i];
ob2[k].afis();
i++;
} while (i != cont);
}
jmp:
cout << "\n\n\n\nStudentii in ordinea medilor sunt: " << endl;
for (int i = 0;i < nr;i++)
{
if (ob2[i].media() < ob2[i + 1].media()) //Not working
{
temp = ob2[i];
ob2[i] = ob2[i + 1];
ob2[i + 1] = temp;
}
}
for (int i = 0;i < nr;i++)
ob2[i].afis();
system("pause");
}
Output: Output
It should be: 9 - 7 - 5
Your bubble sort is broken. A) You need 2 loops. B) you go out of bounds. Change it to something like:
for (int j = 0; j < nr; j++)
{
for (int i = 0;i < nr - 1 ; i++)
{
if (ob2[i].media() < ob2[i + 1].media())
{
temp = ob2[i];
ob2[i] = ob2[i + 1];
ob2[i + 1] = temp;
}
}
}

is there a better way i could have written this program? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
#include <iostream>
using namespace std;
int main()
{
int a;
int b;
int c;
int d;
int e;
int f;
int aa = 0;
int bb = 0;
int cc = 0;
int dd = 0;
int ee = 0;
int ff = 0;
const string odd = "ODD";
const string even = "EVEN";
cout << "enter 6 numbers " << endl;
cin >> a;
cin >> b;
cin >> c;
cin >> d;
cin >> e;
cin >> f;
aa = a % 2;
bb = b % 2;
cc = c % 2;
dd = d % 2;
ee = e % 2;
ff = f % 2;
if(aa == 0){
cout << even << endl;
}else{
cout << odd << endl;
}
if(bb == 0){
cout << even << endl;
}else{
cout << odd << endl;
}
if(cc == 0){
cout << even << endl;
}else{
cout << odd << endl;
}
if(dd == 0){
cout << even << endl;
}else{
cout << odd << endl;
}
if(ee == 0){
cout << even << endl;
}else{
cout << odd << endl;
}
if(ff == 0){
cout << even << endl;
}else{
cout << odd << endl;
}
return 0;
}
for example is there a way to make it do the same thing but with less code, anything I should have included?
is there an easier way than having to write 6 if/else statements - is there a way to do all 6 in one statement or loop?
how could i improve its efficiency?
Write this function:
void outputEvenness(int n)
{
static const string odd = "ODD";
static const string even = "EVEN";
if(n % 2){
cout << odd<< endl;
} else {
cout << even << endl;
}
}
then call it using outputEvenness(a); outputEvenness(b); etc.
First of all you should include header <string>if you use class std::string.
Also there is no sense to define these strings when they are used as string literals. Also instead of different variables it would be better to define only one array. The auxiliary variables are also unnecessary.
If to assume that you may not use arrays then I would write the program the following way
#include <iostream>
#include <initializer_list>
int main()
{
const size_t N = 6;
int a = 0;
int b = 0;
int c = 0;
int d = 0;
int e = 0;
int f = 0;
const char *odd = "ODD";
const char *even = "EVEN";
std::cout << "enter " << N << " numbers: ";
std::cin >> a >> b >> c >> d >> e >> f;
for ( int x : { a, b, c, d, e, f } )
{
if ( x % 2 == 0 )
{
std::cout << x << " is " << even << std::endl;
}
else
{
std::cout << x << " is " << odd << std::endl;
}
}
return 0;
}
If you are allowed to use arrays then the program could look as
#include <iostream>
int main()
{
const size_t N = 6;
int a[N] = {};
const char *odd = "ODD";
const char *even = "EVEN";
std::cout << "enter " << N << " numbers: ";
for ( int &x : a ) std::cin >> x;
for ( int x : a )
{
if ( x % 2 == 0 )
{
std::cout << x << " is " << even << std::endl;
}
else
{
std::cout << x << " is " << odd << std::endl;
}
}
return 0;
}
For this simple program there is no sense to define a separate function that will check whether a number is even or odd because it is this program that is such a function.:)
Use arrays and loops:
int a[6]; // Array of 6 ints
cout << "enter 6 numbers" << endl;
// Input the 6 numbers
for (int i = 0; i < 6; i++)
{
cin >> a[i];
}
// Output the results
for (int i = 0; i < 6; i++)
{
cout << a[i] << " is " << (a[i] & 1 ? "ODD" : "EVEN") << endl;
}
int value = 0;
string response = "";
cout << "enter 6 numbers " << endl;
for(int i=0; i<6; i++)
{
cin >> value;
value % 2 == 0 ? response+="even\n" : response+="odd\n";
}
cout << response;

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;

for loop character printing [closed]

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.