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 8 years ago.
Improve this question
I'm a Java programmer trying to get used to C++ and so far NetBeans is not helping me, I'm having Run Failed(exit value 1, total time: 10ms); I've checked some solutions for problems like mine, but It's not working, so far I'm able to understand that usually this error appears with arrays with non-allocated memory, that is not my case(I Guess).
#include <cstdlib>
#include <iostream>
#include <vector>
using namespace std;
class Rover {
private:
string name;
int position[2];
string direction;
int speed;
public:
Rover();
Rover(string name, int x, int y, string direction, int speed);
void getRoverData();
void setName(string name);
string getName();
void setPosition(int x, int y);
int getPosition();
void setDirection(string diretction);
string getDirection();
void setSpeed(int speed);
int getSpeed();
};
Rover::Rover() {
this->position[0] = 0;
this->position[1] = 0;
this->direction = "North";
}
Rover::Rover(string name, int x, int y, string direction, int speed) {
this->name = name;
this->position[0] = x;
this->position[1] = y;
this->direction = direction;
this->speed = speed;
}
void Rover::setDirection(string direction) {
this->direction = direction;
}
void Rover::setName(string name) {
this->name = name;
}
void Rover::setPosition(int x, int y) {
this->position[0] = x;
this->position[1] = y;
}
void Rover::setSpeed(int speed) {
this->speed = speed;
}
string Rover::getDirection() {
return this->direction;
}
string Rover::getName() {
return this->name;
}
int Rover::getPosition() {
//ToDo -> send array, not value at index, how I can do it?=]
return this->position[0];
}
int Rover::getSpeed() {
return this->speed;
}
void Rover::getRoverData() {
cout << "Rover name is " << this->name << endl;
cout << "The Rover position is(X,Y) " << this->position[0] << "," << this->position[1] << endl;
cout << "Rover is going to " << this->direction << endl;
cout << "Rover speed is(M/s) " << this->speed << endl;
}
int main(int argc, char** argv) {
//vector<Rover> *vectorOfRover = new vector<Rover>();
vector<Rover> vectorOfRover;
int i = 0;
while (sizeof (vectorOfRover) <= 5) {
string tempName;
int tempX;
int tempY;
string tempDirection;
int tempSpeed;
cout << "Enter Rover name " << endl;
cin >> tempName;
cout << "Enter X position " << endl;
cin >>tempX;
cout << "Enter Y position " << endl;
cin >> tempY;
cout << "Enter the Rover direction " << endl;
cin >> tempDirection;
cout << "Enter the Rover speed " << endl;
cin >> tempSpeed;
Rover r1 = Rover(tempName, tempX, tempY, tempDirection, tempSpeed);
vectorOfRover.push_back(r1);
i++;
}
for (int j = 0; j <= i; j++) {
Rover r = vectorOfRover[j];
r.getRoverData();
}
return 0;
}
This line doesn't make sense:
while (sizeof (vectorOfRover) <= 5) {
sizeof operator is evaluated at compile time, so it doesn't depend on the actual number of items in the vector. Most likely sizeof(std::vector) is greater than 5 so you skip the loop completely. What you meant is probably
while (vectorOfRover.size() <= 5) {
And then you go out of bounds here:
for (int j = 0; j <= i; j++) {
Change it to
for (int j = 0; j < i; j++) {
I think part of the problem is calling sizeof on a vector. That just does not make any sense: sizeof is a compile time operator that returns the size in memory of a certain object, thus it will never return the number of elements in a collection, e.g., see this.
Related
So for my program It is suposed to read from a file and display my information but the display is misbehaving. I have asked my collegues and they are unsure and I even asked my professor but he was unsure of what was causing the error. If anyone could help me I would be very very thankful and honnostly amazed
//LIBRARIES
#include <iostream>
#include <iomanip>
#include <fstream>
#include <stdio.h>
#include <math.h>
#include <cmath>
#include <string>
#include <cstring>
#include <thread>
#include <stdexcept>
#include <limits>
#include <cctype>
using namespace std;
//STORED ARRAY NAMES AND FUNCTION NAMES
int fillArrays (string teamWin[], string teamLose[],
float theScore[], ifstream & final);
float pointAverage (float theScore[], float numberOfGames);
int teamsScoredForty (float theScore[], int gameNum);
int savedMax (float theScore[], int gameNum);
int savedMin (float theScore[], int gameNum);
void printStoredInformation (string teamWin[], string teamLose[],
float theScore[], int gameNum);
void finalDisplay (float theScore[], string teamWin[],
string teamLose[], int teamsOverForty,
float averagePoints, int maxSavedInfo, int minSavedInfo);
//START OF MAIN
int
main ()
{
ifstream final;
float theScore[100];
string teamWin[100];
string teamLose[100];
int gameNum;
float numberOfGames;
float averagePoints;
int teamsOverForty;
int maxSavedInfo;
int minSavedInfo;
gameNum = fillArrays (teamWin, teamLose, theScore, final);
numberOfGames = gameNum;
averagePoints = pointAverage (theScore, numberOfGames);
teamsOverForty = teamsScoredForty (theScore, gameNum);
maxSavedInfo = savedMax (theScore, gameNum);
minSavedInfo = savedMin (theScore, gameNum);
printStoredInformation (teamWin, teamLose, theScore, gameNum);
finalDisplay (theScore, teamWin, teamLose, teamsOverForty,
averagePoints, maxSavedInfo, minSavedInfo);
return 0;
}
//FINAL DISPLAY OF INFORMATION
void
finalDisplay (float theScore[], string teamWin[],
string teamLose[], int teamsOverForty[],
float averagePoints, int maxSavedInfo, int minSavedInfo)
{
cout << "AVERAGE = " << averagePoints << endl;
cout << "TEAMS WHO SCORED OVER 40 POINTS IN ONE GAME = " << teamsOverForty << endl;
cout << endl;
cout << endl;
cout << "TEAM WHO SCORED THE MOST POINTS IN ONE GAME" << endl;
cout << "WINNERS = " << teamWin[maxSavedInfo] << endl;
cout << "LOSERS = " << teamLose[maxSavedInfo] << endl;
cout << "FINAL SCORE OF WINNERS" << theScore[maxSavedInfo] << endl;
cout << endl;
cout << endl;
cout << "TEAM WHO SCORED THE LEAST POINTS AND STILL WON" << endl;
cout << "WINNERS = " << teamWin[minSavedInfo];
cout << "LOSERS = " << teamLose[minSavedInfo];
cout << "FINAL SCORE OF WINNERS = " << theScore[minSavedInfo];
cout << endl;
}
//INFORMATION STORAGE FOR ARRAYS
int
fillArrays (string teamWin[], string teamLose[],
float theScore[], ifstream & final)
{
int i = 0;
final.open ("superbowl.dat");
while (!final.eof ())
{
getline (final, teamWin[i]);
getline (final, teamLose[i]);
final >> theScore[i];
final.ignore (1, '\n');
i += 1;
}
final.close ();
return i;
}
//FUNCTION TO FIND AVERAGE OF THE TEAMS SCORE
float
pointAverage (float theScore[], float numberOfGames)
{
float sum;
float avg;
for (int i = 0; i < numberOfGames; i++)
{
sum = sum + theScore[i];
}
avg = sum / numberOfGames;
return avg;
}
//FUNCTION FOR ALL THE TEAMS WHO SCORED MORE THEN FORTY
int
teamsScoredForty (float theScore[], int gameNum)
{
int teamSavedScoreOverForty = 0;
for (int i = 0; i < gameNum; i++)
{
if (theScore[i] > 40)
{
teamSavedScoreOverForty = teamSavedScoreOverForty + 1;
}
}
return teamSavedScoreOverForty;
}
//FUNCTION TO FIND WHICH TEAM SCORED MORE THEN ANY OTHER TEAM AND WON
int
savedMax (float theScore[], int gameNum)
{
int val = -1;
int idx;
for (int i = 0; i < gameNum; i++)
{
if (val < theScore[i])
{
val = theScore[i];
idx = 1;
}
}
return idx;
}
//FUNCTION TO FIND WHICH TEAM SCORED LESS THEN ANY OTHER TEAM AND WON
int
savedMin (float theScore[], int gameNum)
{
int val = theScore[0];
int idx;
for (int i = 0; i < gameNum; i++)
{
if (theScore[i] < val)
{
idx = i;
}
}
return idx;
}
//FINAL DISPLAY FUNCTION FOR ALL OF THE INFORMATION ABOVE
void
printStoredInformation (string teamWin[], string teamLose[],
float theScore[], int gameNum)
{
int a = 1;
for (int i = 0; i < gameNum; i++)
{
cout << "SUPER BOWL " << a << endl;
cout << "NAME OF WINNING TEAM - " << teamWin[i] << endl;
cout << "NAME OF LOSING TEAM - " << teamLose[i] << endl;
cout << "TOTAL POINTS SCORED BY WINNERS - " << theScore[i] << endl;
cout << endl;
a = a + 1;
}
}
That is the main code that it is having errors with.
PackersChiefs35PackersRaiders33JetsColts16ChiefsVikings23ColtsCowboys16CowboysDolphins24DolphinsRedskins14
DolphinsVikings24SteelersVikings16SteelersCowboys21RaidersVikings32CowboysBroncos27Broncos27SteelersVikings
35SteelersRams31RaidersEagles2749ersBengals26RedskinsDolphins27RaidersRedskings3849ersDolphins38Bears
Patriots46GiantsBroncos39RedskinsBroncos4249ersBengals2049ersBroncos55GiantsBills20RedskinsBills37Cowboys
Bills52CowboysBills3049ersChargers49CowboysSteelers27PackersPatriots35BroncosPackers31BroncosFalcons34
RamsTitans23RavensGiants34Patriotsrams20BuccaneersRaiders48PatriotsPanthers32PatriotsEagles24Steelers
Seahawks21ColtsBears29GiantsPatriots17SteelersCardinals27SaintsColts31PackersSteelers31GiantsPatriots
21Ravens49ers34SeahawksBroncos43PatriotsSeahawks28BroncosPanthers24PatriotsFalcons34EaglesPatriots41
PatriotsRams13Chiefs49ers31BuccaneersChiefs31RamsBengals23
Between Each word is an enter, I am just not alloud to put it in on this website sadly. It says it looks like Spam
I tried to mess with the 2 different displays I have and I tried to even add more functions to kep things more organized but it did not work. I also spent a few hours trying to debug it.
In addition to the concerns expressed by other users in the comments, your output is broken because you have a typo in your input file on record 13. You repeated Bronco 27 twice and the file input function breaks because it expects two team names and then an integer. Instead it receives a team name followed by a number:
SUPER BOWL 12
NAME OF WINNING TEAM - Cowboys
NAME OF LOSING TEAM - Broncos
TOTAL POINTS SCORED BY WINNERS - 27
SUPER BOWL 13
NAME OF WINNING TEAM - Broncos
NAME OF LOSING TEAM - 27
TOTAL POINTS SCORED BY WINNERS - 0
//...
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 2 months ago.
Improve this question
This has somehow become susceptible to buffer overflow. Not sure why or how to fix it?
ps. I am new to programming and any tips to improve the overall quality of the code would be greatly appreciated.
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int numberSeries[] = { 1 };
int seriesSize;
int checkOrder = 1;
int counter = 0;
int i = 0;
string arr[] = { "test" };
string value;
string import;
string fileLocation;
void CreateArrayFromFile(string fileLocation);
void InputNumbers();
void PrintArray();
int Iteration(int size, int array[]);
void SwapNumbers(int arrayLocation, int array[]);
int main()
{
cout << "What you like to numbers 'import' from file or 'manually' enter the numbers? \n";
cin >> import;
if (import == "import") {
cout << "Input file location using full path: ";
cin >> fileLocation;
CreateArrayFromFile(fileLocation);
}
else if (import == "manually") {
InputNumbers();
PrintArray();
while (counter < seriesSize) {
Iteration(seriesSize, numberSeries);
}
}
else {
cout << "INVALID SELECTION";
}
}
void InputNumbers() {
cout << "What is the required size of the array? \n";
cin >> seriesSize;
cout << "Enter " << seriesSize << " numbers: \n";
for (int i = 0; i < seriesSize; i++) {
cin >> numberSeries[i];
}
cout << "\n";
}
void PrintArray() {
cout << "Here are your current numbers: \n";
for (int i = 0; i < seriesSize; i++) {
cout << numberSeries[i] << " ";
}
cout << "\n";
}
int Iteration(int size, int array[]) {
for (int i = 0; i < (seriesSize - 1); i++) {
if (numberSeries[i] > numberSeries[i + 1]) {
SwapNumbers(i, numberSeries);
counter = 0;
}
else if (numberSeries[i] <= numberSeries[i + 1]) {
counter++;
}
}
if (counter >= seriesSize) {
cout << "YOUR NUMBERS HAVE BEEN SORTED\n\n";
}
else {
PrintArray();
cout << "Iteration complete!\n\n";
}
return 0;
}
void SwapNumbers(int arrayLocation, int array[]) {
int tempSwapOne, tempSwapTwo;
//store each number
tempSwapOne = array[arrayLocation];
tempSwapTwo = array[arrayLocation + 1];
//assign number to new location
array[arrayLocation] = tempSwapTwo;
array[arrayLocation + 1] = tempSwapOne;
}
void CreateArrayFromFile(string fileLocation) {
ifstream file;
file.open(fileLocation, ios::in);
int* ptr = (int*)malloc(sizeof(file));
cout << *ptr;
string line;
int i = 0;
if (file.is_open()) {
while (!file.eof())
{
getline(file, line);
arr[i] = line;
i++;
}
seriesSize = i;
}
else {
cout << "File could not be opened. Check path is correct...\n\n";
return;
}
for (i = 0; i < seriesSize; i++) {
int tempNumber = stoi(arr[i]);
numberSeries[i] = tempNumber;
cout << numberSeries[i] << " ";
}
cout << "\nTotal numbers: " << seriesSize;
}
I tried to assign the correct amount of memory but I have no idea how to figure out the correct amount.
Use std::vector instead. It handles the memory management and will automatically resize.
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 6 years ago.
Improve this question
I'm writing a program that calculates the batting averages of a user defined number of players. The program displays the name of a player, their number of times at bat, number of hits, and their batting average. Finally, it displays the total number of times the players were at bat, the total number of hits, and the overall average. For some reason, the functions that calculate the individual player average and overall average are returning 0. It's probably something small, but I'm stumped as to how to try and fix it.
//Batting Average Calculator
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
//Create Structure
struct Record
{
string name;
int AB;
int hit;
double avg;
};
int getSize(int);
void getData(Record[], int );
int calculateTotalAB(Record[], int, int);
int calculateTotalHit(Record[], int, int);
double calculateTotalAvg(Record[], int, double);
void calculateAvg(Record[], int);
void display(Record[], int, int , int, double);
int main()
{
const int MaxSize = 50;
Record players[MaxSize];
int size = 0;
int totalAB = 0;
int totalHit = 0;
double totalAvg = 0;
size = getSize(size);
getData(players, size);
totalAB = calculateTotalAB(players, size, totalAB);
totalHit = calculateTotalHit(players, size, totalHit);
calculateAvg(players,size);
totalAvg = calculateTotalAvg(players, size, totalAvg);
display(players, size, totalHit, totalAB, totalAvg);
}
//get number of players to be calculated
int getSize(int size)
{
cout << "Please enter the number of players on the team: ";
cin >> size;
return size;
}
//get Player name, AB, and hit
void getData(Record players[], int size)
{
string dummy;
getline(cin, dummy);
for (int i = 0; i < size; i++)
{
cout << "Please input the name of student " << i + 1 << ": ";
getline(cin, players[i].name);
cout << "Please input the number of times "<< players[i].name << " was at bat: ";
cin >> players[i].AB;
cout << "Please input the number of hits for " << players[i].name << ": ";
cin >> players[i].hit;
cout << " " << endl;
getline(cin, dummy);
}
}
int calculateTotalAB(Record players[], int size, int totalAB)
{
for (int i = 0; i < size; i++)
{
totalAB = totalAB + players[i].AB;
}
return totalAB;
}
int calculateTotalHit(Record players[], int size, int totalHit)
{
for (int i = 0; i < size; i++)
{
totalHit = totalHit + players[i].hit;
}
return totalHit;
}
void calculateAvg(Record players[], int size)
{
for (int i = 0; i < size; i++)
{
players[i].avg = players[i].hit / players[i].AB;
}
}
double calculateTotalAvg(Record players[], int size, double totalAvg)
{
double j = 0;
for (int i = 0; i < size; i++)
{
j = j + players[i].avg;
}
totalAvg = j / size;
return totalAvg;
}
void display(Record players[], int size, int totalHit, int totalAB, double totalAvg)
{
cout << fixed << showpoint << setprecision(3);
cout << "Player AB Hit Avg" << endl;
cout << " " << endl;
for (int i = 0; i < size; i++)
{
cout << players[i].name << setw(8) << players[i].AB << setw(5) << players[i].hit << setw(5) << players[i].avg;
}
cout << " " << endl;
cout << "Totals " << totalAB << " " << totalHit << " " << totalAvg << endl;
}
You are dividing an int by an int, which is calculated as an int, and storing it in a double. What you have to do is explicitly cast at least one of your int values to a double first, like this:
void calculateAvg(Record players[], int size)
{
for (int i = 0; i < size; i++)
{
players[i].avg = players[i].hit / (double) players[i].AB;
}
}
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
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.