I've got a class assignment in C++ that basically wants to me to use a struct and as well an array or two to allow customers to view and select items from a breakfast menu. Whenever I go to run the program it just says that it exited with a return value of 0. I've tried spot checking and I can't figure out what's wrong. I suspect I may not be loading the data from the text file correctly and thus it's causing no results because no data is loaded.
Here is my code:
//Student Name: Jacob Gillespie
//Date: 10/18/13
//Program: Breakfast Billing System
//Summary: Program allows customer to select different items from a menu and sums up
their total
//Headers
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
//Define structs
struct menuItemType
{
string menuItem;
double menuPrice;
};
//Declare variables and arrays
ifstream inData;
const double tax = 0.05;
int itemSelected[8];
menuItemType menuList[8];
//Provide function prototypes
void getData(ifstream& inFile);
void showMenu();
void printCheck();
void customerSelection();
//Main Program Execution
int main()
{
//Initialize itemSelected to 0
for (int counter = 0; counter < 8; counter++)
itemSelected[counter] = 0;
//Open input file
inData.open("menu.txt");
//Execute functions
void getData(ifstream& inData);
void showMenu();
void customerSelection();
void printCheck();
inData.close();
return 0;
}
//Function Definitions
//getData
void getData(ifstream& inFile)
{
for (int counter = 0; counter < 8; counter++)
{
inData >> menuList[counter].menuItem
>> menuList[counter].menuPrice;
}
}
//showMenu
void showMenu()
{
for (int counter = 0; counter < 8; counter++)
cout << menuList[counter].menuItem << " " << menuList[counter].menuPrice << endl;
}
//printCheck
void printCheck()
{
double total = 0;
double addedTax = 0;
for (int counter = 0; counter < 8; counter++)
if (itemSelected[counter] = 1)
{
cout << menuList[counter].menuItem << " " << menuList[counter].menuPrice << endl;
total = total + menuList[counter].menuPrice;
}
addedTax = total * tax;
cout << "Tax " << addedTax << endl;
cout << "Amount Due " << total << endl;
}
//customerSelection
void customerSelection()
{
string choice;
for (int counter = 0; counter < 8; counter++)
{
cout << "If you would like to order the item, " << menuList[counter].menuItem << ", please enter 'yes'. "
<< endl << "If not, please enter 'no'." << endl;
if (choice == "yes")
itemSelected[counter] = 1;
}
}
The voids before all the function calls in main are unnecessary where you have
//Execute functions
Related
`
#include <iostream>
#include <iomanip>
using namespace std;
void getGrades(double g[], const int SIZE)
{
cout << "Please enter " << SIZE << " grades:" << endl;
for(int i = 0; i < SIZE; i++)
{
cin >> g[i];
}
}
double getAverage(double g[], const int SIZE)
{
int total = 0;
for(int i = 0; i < SIZE; i++)
{
total += g[i];
}
return total/SIZE;
}
void findDropInfo(double g[], const int SIZE, int &lowest, double average)
{
int total = 0;
lowest = g[0];
for(int i = 1; i < SIZE; i++)
{
if (lowest > g[i]) {
lowest = g[i];
}
}
average = (total - lowest)/SIZE;
return average;
}
void printData(double g[], int lowest, double average, double avg_before)
{
cout << "The 5 grades entered by the user are:" << endl;
cout << g[];
cout << "Grade dropped: " << lowest << endl;
cout << "Final Average: " << average << endl;
cout << "Average before drop: " << avg_before << endl;
}
// TODO: Complete the function definitions
int main()
{
const int SIZE = 5;
double grades[SIZE];
int lowest;
double avg,
avgBeforeDrop;
// TODO: Add function calls
getGrades(grades[SIZE], SIZE);
getAverage(grades[SIZE], SIZE);
findDropInfo(grades[SIZE], SIZE, lowest, avg);
printData(grades[SIZE], lowest, avg, avgBeforeDrop);
return 0;
}
`
Whenever I run the program, I get multiple errors saying there's no matching candidate function. I'm not sure if the problems are in the functions themselves or in the function calls, but from what I know the functions themselves should be fine. I'm also told there's an expected expression in g[] but I' not sure what's wrong there either, as it's meant to be empty.
Most issues have already been resolved in the comments, but note: cout << g[] does not print the elements of g.
The way to do this is
char separator = /* the character you want to use to separate the printed elements of g */
for (int i = 0; i < SIZE; i++)
{
cout << g[i] << separator;
}
if (separator != '\n') cout << '\n'; //this is to put the next print on the next line
I would put this as a comment but I don't have enough reputation :|
I am in a C++ class and I am having trouble with the project. The idea of the project is to create an ordering application using structs and arrays. As far as I can tell the program is working as intended except for the how many items of each item the person ordered part of my printMenu function. If I am mistaken and or you find more errors please let me know.
Here is the code:
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
using namespace std;
struct dinnerItemType
{
string dinnerItem;
double dinnerPrice;
int dinnerOrdered;
};
void getFood(dinnerItemType ourMenu[], int &size);
void printMenu(dinnerItemType ourMenu[], int size);
void printCheck(dinnerItemType ourMenu[], int size);
//Defines the global tax constant of 6%
const double TAX = 0.06;
int main()
{
dinnerItemType ourMenu[150];
int size = 0;
getFood(ourMenu, size);
printMenu(ourMenu, size);
printCheck(ourMenu, size);
system("pause");
return 0;
}
void getFood(dinnerItemType ourMenu[], int &size)
{
ourMenu[0].dinnerItem = "Chicken Sandwich";
ourMenu[0].dinnerPrice = 4.45;
ourMenu[0].dinnerOrdered = 0;
ourMenu[1].dinnerItem = "Fries";
ourMenu[1].dinnerPrice = 2.47;
ourMenu[1].dinnerOrdered = 0;
ourMenu[2].dinnerItem = "Truffle Fries";
ourMenu[2].dinnerPrice = 0.97;
ourMenu[2].dinnerOrdered = 0;
ourMenu[3].dinnerItem = "Filet 8oz";
ourMenu[3].dinnerPrice = 11.99;
ourMenu[3].dinnerOrdered = 0;
ourMenu[4].dinnerItem = "Fruit Basket";
ourMenu[4].dinnerPrice = 2.44;
ourMenu[4].dinnerOrdered = 0;
ourMenu[5].dinnerItem = "Tea";
ourMenu[5].dinnerPrice = 0.69;
ourMenu[5].dinnerOrdered = 0;
ourMenu[6].dinnerItem = "Water";
ourMenu[6].dinnerPrice = 0.25;
ourMenu[6].dinnerOrdered = 0;
size = 7;
}
void printMenu(dinnerItemType ourMenu[], int size)
{
int number;
int amount;
cout << "Welcome to the restraunt here are your menu items: \n";
for (int i = 0; i < size; i++)
{
cout << (i + 1) << ")";
cout << ourMenu[i].dinnerItem
<< "$"
<< ourMenu[i].dinnerPrice
<< endl;
}
cout << "To order just type in the number associated with the menu item and hit enter.\n"
<< "Once you have completed your order just type in 0 to go to checkout.\n";
cin >> number;
while (number != 0)
{
if (number >= 1 && number <= 8)
{
ourMenu[number - 1].dinnerOrdered++;
}
else
{
cout << "The number does not coorispond with a menu item please try again.\n";
}
cout << "To order just type in the number associated with the menu item and hit enter.\n"
<< "Once you have completed your order just type in 0 to go to checkout.\n";
cin >> number;
}
}
void printCheck(dinnerItemType ourMenu[], int size)
{
double total = 0;
cout << "Your Bill: ";
for (int i = 0; i < size; i++)
{
if (ourMenu[i].dinnerOrdered > 0)
{
total += ourMenu[i].dinnerPrice;
}
}
cout << "Tax: $ " << fixed << setprecision(2) << (total * TAX);
cout << " Ammount Due: $" << (total + (total * TAX)) << endl;
cout << "Thank you come again!" << endl;
}
This line:
total += ourMenu[i].dinnerPrice;
is only adding the cost of one meal to the total, regardless of how many times that meal is ordered.
To fix it: simply multiple the price by the number of times it is ordered:
total += ourMenu[i].dinnerPrice * ourMenu[i].dinnerOrdered;
it's my first time working with classes and headers in C++ and I ran into these errors after putting together my code
function does not take 1 arguments // For all 4 functions
overloaded member function not found in 'Animals' // Also for all 4 fncs
syntax error: identifier 'fstream' // header file error
The program is designed to read and write to a file, while also doing searches and being able to manipulate the binary file. I'm pretty sure the error is in my declarations somewhere but I can't figure it out myself; any help is appreciated.
main.cpp
#include <iostream>
#include<iomanip>
#include <fstream>
#include"animals.h"
using namespace std;
int main()
{
Animals nA;
fstream animalFile;
int choice;
cout << setprecision(2) << fixed;
do
{
// Display the menu.
cout << "\n1. Add a new animal\n";
cout << "2. Remove an animal\n";
cout << "3. Search and display a animal\n";
cout << "4. Display all animals\n";
cout << "5. Exit\n";
do
{
cout << "Enter your choice (1-5): ";
cin >> choice;
} while (choice < 1 || choice > 5);
// Process the selection.
switch (choice)
{
// Choice 1 is to add an animal
case 1:
nA.addAnimal(animalFile);
break;
// Choice 2 is to remove an animal
case 2:
nA.removeAnimal(animalFile);
break;
// Choice 3 is to search and display 1 animal
case 3:
nA.searchAnimal(animalFile);
break;
// Choice 4 is to display all animals
case 4:
nA.displayAnimal(animalFile);
}
} while (choice != 5);
system("pause");
return 0;
}
Animals.h
#ifndef ANIMALS_H
#define ANIMALS_H
#include <string>
#include <iostream>
#include <fstream>
class Animals
{
private :
std::string name;
int age;
public :
//Default constructor
Animals();
//Create an animal object
Animals(std::string name, int age);
//Add a new animal record
void addAnimal(fstream &d);
//Remove an animal record
void removeAnimal(fstream &d);
//Displays an animal through a search
void searchAnimal(fstream &d);
//Display ALL animals
void displayAnimal(fstream &d);
};
#endif
Animals.cpp
#include <iostream>
#include <iomanip>
#include <string>
#include <fstream>
#include "Animals.h"
using namespace std;
Animals::Animals()
{
name = "NULL";
age = 0;
}
Animals::Animals(std::string name, int age)
{
Animals *newAnimal = new Animals;
}
void Animals::addAnimal(fstream &d)
{
string userName;
int userAge = 0;
int stringRemainder;
int record;
const int RECORD_SIZE = 40;
//Collecting user input
do
{
std::cout << "Please enter your animal name: ";
std::cin >> userName;
std::cout << "\n";
} while (sizeof(userName) > 30);
do
{
std::cout << "Please enter your animal age: ";
std::cin >> userAge;
std::cout << "\n";
} while (userAge <= 0 || !isdigit(userAge));
//Fixing length of string
stringRemainder = 30 - sizeof(userName);
//Finds record number based on position
record = (d.tellg() % RECORD_SIZE) + 1;
//Writing to file
d.close();
d.open("animals.txt", std::ios_base::app | ios::binary);
d << record << "";
d << userName;
for (int i = 0; i < stringRemainder; i++)
{
d << "";
}
d << userAge << "\n";
d.close();
}
void Animals::removeAnimal(fstream &d)
{
int recordNumber = 0;
const int RECORD_SIZE = 40;
char recordBuffer[RECORD_SIZE];
d.open("animals.txt", ios::out| ios::in |ios::binary);
//Collecting user input
do
{
cout << "Enter the record of the animal to be removed: ";
cin >> recordNumber;
} while (recordNumber <= 0 || !isdigit(recordNumber));
// move pointer to desired position, and overwrite!
d.seekp((recordNumber-1) * RECORD_SIZE);
d.write(recordBuffer, RECORD_SIZE);
d.close();
}
void Animals::searchAnimal(fstream &d)
{
int userRecord = 0;
char displayRecord[2];
const int RECORD_SIZE = 40;
char fileOutput[RECORD_SIZE];
string displayInfo;
char displayName[RECORD_SIZE];
char displayAge[2];
int i,k;
int j = 0;
d.open("animals.txt", ios::out | ios::binary);
//Getting user input
do
{
cout << "Enter the record of the animal to be diplayed: ";
cin >> userRecord;
} while (userRecord <= 0 || !isdigit(userRecord));
//Moving pointer position to searched value
d.seekp((userRecord - 1) * RECORD_SIZE);
//Gets data from file, stores into displayInfo
getline(d, displayInfo);
d.close();
//Entering file data into diplay variables,
//value 'i' increments through entire displayInfo array
for (i = 0; isdigit(displayInfo[i]); i++)
{
displayRecord[i] = displayInfo[i];
}
//New sentinel for ONLY string cap including buffer
k = i + 30;
for (i; i < k; i++)
{
displayName[j] = displayInfo[i];
j++;
}
//Finishes off last of the displayInfo array
for (i; i < sizeof(displayInfo); i++) {
displayAge[i] = displayInfo[i];
}
//Prints the data for user
cout << "For record number: " << userRecord << "\n";
cout << "Animal: ";
for (int i = 0; i < strlen(displayName); i++)
{
cout << displayName[i];
}
cout << "\n";
cout << "Age: ";
for (int i = 0; i < strlen(displayAge); i++)
{
cout << displayAge[i];
}
cout << "\n";
}
//Mostly copied from above function, displays ALL animals
void Animals::displayAnimal(fstream &d)
{
int userRecord = 0;
char displayRecord[2];
const int RECORD_SIZE = 40;
char fileOutput[RECORD_SIZE];
string displayInfo;
char displayName[RECORD_SIZE];
char displayAge[2];
int numberOfRecords;
int i, k;
int j = 0;
int q = 0;
d.open("animals.txt", ios::out | ios::in | ios::binary);
d.seekg(0, d.end);
numberOfRecords = d.tellg() % RECORD_SIZE;
d.seekg(0, d.beg);
for (int q; q < numberOfRecords; q++) {
d.seekp(q * RECORD_SIZE);
//Gets data from file, stores into displayInfo
getline(d, displayInfo);
//Entering file data into diplay variables,
//value 'i' increments through entire displayInfo array
for (i = 0; isdigit(displayInfo[i]); i++)
{
displayRecord[i] = displayInfo[i];
}
//New sentinel for ONLY string cap including buffer
k = i + 30;
for (i; i < k; i++)
{
displayName[j] = displayInfo[i];
j++;
}
//Finishes off last of the displayInfo array
for (i; i < sizeof(displayInfo); i++) {
displayAge[i] = displayInfo[i];
}
//Prints the data for user
cout << "For record number: " << userRecord << "\n";
cout << "Animal: ";
for (int i = 0; i < strlen(displayName); i++)
{
cout << displayName[i];
}
cout << "\n";
cout << "Age: ";
for (int i = 0; i < strlen(displayAge); i++)
{
cout << displayAge[i];
}
cout << "\n\n";
}
d.close();
}
The headers <iostream> and <fstream> bring their symbols into the std namespace, so any reference to these symbols in the header need to be fully qualified; e.g. std::fstream. Also, you might want to include <iosfwd> in your headers instead - this minimizes the compiler time cost of importing the header, assuming that the header only uses reference to the symbols mentioned in the iostream header.
You should use ifstream for read files and ofstream for write files.
And in header file, you should use std::ifstream & d or std::ofstream & d in argument of 4 functions.
So I'm trying to create an array that contains some user inputted names, and then associate those names with letter grades from tests (ex: A, B, C, D, F). My question is, how would I use an array to accept the user inputted names?
EDIT:
Sorry this is a bit long, I don't know what part to put that would help out. Totally new to C++ and I can't seem to find anything online regarding the matter, lol.
Here is some code. This program currently asks the user for test scores, then displays and drops the lowest test score, and finally, calculates the average of the scores without the lowest one. The end goal is to ask the user for 5 students names, and 4 scores for each student, then dropping the lowest score for each student and calculating the averages of ALL scores inputted regardless of student.
#include <iostream>
#include <string>
using namespace std;
void getScore(int &);
int findLowest(int [], int);
void calcAverage(int [], int);
int main () {
const int NUM_SCORES = 5;
int scores[NUM_SCORES];
cout << "Welcome to test averages." << endl;
cout << "Please enter scores for " << NUM_SCORES << " students." << endl;
cout << endl;
for (int i = 0; i < NUM_SCORES; i++) {
getScore(scores[i]);
}
for (int i = 0; i < NUM_SCORES; i++) {
cout << "Score " << (i + 1) << ": " << scores[i] << endl;
}
cout << endl;
cout << "The lowest of these scores is " << findLowest(scores, NUM_SCORES) << endl;
calcAverage(scores, NUM_SCORES);
return 0;
}
void getScore(int & s) {
s = -1;
cout << "Please enter a test score: ";
cin >> s;
while (s < 0 || s > 100) {
cout << "Score range must be from 0-100" << endl;
cout << "Please re-enter a score: ";
cin >> s;
}
}
int findLowest(int theArray [], int theArraySize) {
int lowest = theArray[0];
for (int i = 1; i < theArraySize; i++) {
if (theArray[i] < lowest) {
lowest = theArray[i];
}
}
return lowest;
}
void calcAverage(int theArray [], int theArraySize) {
int sum = 0;
for (int i = 0; i < theArraySize; i++) {
sum += theArray[i];
}
double average = (sum - findLowest(theArray, theArraySize)) / (theArraySize - 1.0);
cout << "The average is " << average << endl;
}
Try getline from #include <string>
std::string names[5];
for (int i = 0; i < 5; ++i){
getline(std::cin, names[i]);
}
Please help me with my homework. I've got this program working just fine in debug mode, but as soon I use release mode it crashes with an abort().
I know it probably has something to do with memory allocation, but I don't understand pointers well enough.
Requirement is that I have to use an *array to dynamically allocate memory.
"Your program should work for any number of students. When the program
starts, it should ask the user for the number of students to be
processed. Then it should dynamically allocate an array of that size
(array of student/score structures)."
I then need to, "Call a function to input the student name/score pairs and store them in the array."
So should I create the array in main or inside of the function? How can I return/pass the *array without messing up memory allocation?
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
struct Student
{
string name; //student's name
int score; //student's score
};
//function prototypes
void inputNameScore(Student*, int&);
void sortArray(Student* , int);
double avgScore(Student* , int);
void displayTable(Student* , int, double);
int main()
{
Student* arrayOfStudentPtr; //pointer of type student to receive returned array pointer
int numberOfStudents; //number of students to be entered by user
double average; //total score average
cout << "Please enter the number of students: ";
cin >> numberOfStudents;
arrayOfStudentPtr = new Student[numberOfStudents]; //dynamic array of type Student assigned to pointer
inputNameScore(arrayOfStudentPtr, numberOfStudents);
sortArray(arrayOfStudentPtr, numberOfStudents);
average = avgScore(arrayOfStudentPtr, numberOfStudents);
displayTable(arrayOfStudentPtr, numberOfStudents, average);
return 0;
}
void inputNameScore(Student* arrayOfStudentPtr, int& numberOfStudents)
{
for (int i = 0; i < numberOfStudents; i++)
{
cout << endl << "Enter the name for student " << i + 1 << ": ";
cin.ignore();
getline(cin, arrayOfStudentPtr[i].name);
cout << endl << "Enter the student's score: ";
cin >> arrayOfStudentPtr[i].score;
while (arrayOfStudentPtr[i].score > 105 || arrayOfStudentPtr[i].score < 0)
{
cout << "Student's score can't be negative or greater than 105." << endl;
cout << endl << "Enter the student's score: ";
cin >> arrayOfStudentPtr[i].score;
}
}
}
void sortArray(Student* arrayOfStudentPtr, int numberOfStudents)
{
Student Temp; //holds a student struct object
bool swap; //swap is initialized to false at the start of each loop. If it is still false at end of loop we know there is nothing else to sort
do
{
swap = false;
for (int i = 0; i < numberOfStudents; i++)
{
if (arrayOfStudentPtr[i].score > arrayOfStudentPtr[i + 1].score)
{
Temp = arrayOfStudentPtr[i];
arrayOfStudentPtr[i] = arrayOfStudentPtr[i + 1];
arrayOfStudentPtr[i + 1] = Temp;
swap = true;
}
}
} while (swap);
}
double avgScore(Student* arrayOfStudentPtr, int numberOfStudents)
{
int total; //total of all grades
double average; //average of all grades
total = 0;
for (int i = 0; i < numberOfStudents; i++)
{
total = arrayOfStudentPtr[i].score;
}
average = total / numberOfStudents;
//average = static_cast<double>(total) / numberOfStudents;
return average;
}
void displayTable(Student* arrayOfStudentPtr, int numberOfStudents, double average)
{
cout << endl << setw(31) << left << "Name" << setw(6) << right << "Score" << endl;
cout << "-------------------------------------" << endl;
for (int i = 0; i < numberOfStudents; i++)
{
cout << setw(31) << left << arrayOfStudentPtr[i].name << setw(6) << right << arrayOfStudentPtr[i].score << endl;
}
cout << "-------------------------------------" << endl;
cout << setw(31) << left << "Average: " << setw(6) << right << endl;
}
The following code will work.
void sortArray(Student* arrayOfStudentPtr, int numberOfStudents)
{
Student Temp; //holds a student struct object
bool swap; //swap is initialized to false at the start of each loop. If it is still false at end of loop we know there is nothing else to sort
do
{
swap = false;
for (int i = 0; i < numberOfStudents-1; i++)
{
if (arrayOfStudentPtr[i].score > arrayOfStudentPtr[i + 1].score)
{
Temp = arrayOfStudentPtr[i];
arrayOfStudentPtr[i] = arrayOfStudentPtr[i + 1];
arrayOfStudentPtr[i + 1] = Temp;
swap = true;
}
}
} while (swap);
}