As part of a homework assignment, I am supposed to write a program that simulates queues in a grocery store environment. The full assignment is explained on the linked page.
I have the program working when there is only one queue, and am trying to modify it to handle multiple queues, per the assignment description. However, I am getting a few errors when compiling.
I know the issue has to do with dequeueing a customer in line; I'm just not sure how to modify the program so it works with multiple queues.
Any assistance is greatly appreciated!
Error Messages:
qsim.cpp: In function 'int main()':
qsim.cpp:64: error: request for member 'empty' in 'line', which is of non-class type 'Queue [(((long unsigned int)(((long int)queuecount) - 1)) + 1u)]'
qsim.cpp:66: error: request for member 'dequeue' in 'line', which is of non-class type 'Queue [(((long unsigned int)(((long int)queuecount) - 1)) + 1u)]'
Main ProgramThe main program includes a class called Queue. I know the code is correct for this, since it works perfectly in a different test program.
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include "queue.h"
using namespace std;
int shortest_queue(Queue q[], int queuecount)
{
int shortest = 0;
for (int i = 1; i < queuecount; ++i)
{
if(q[i].size() < q[shortest].size())
shortest = i;
}
return shortest;
}
int queue_total(Queue q[], int queuecount)
{
int custcount = 0;
for (int i = 0; i < queuecount; ++i)
custcount += q[i].size();
return custcount;
}
int main()
{
int trans_time = 0;
int count = 0;
int entry_time;
int wait_sum = 0;
int wait_time = 0;
int seed;
int ARV_PROB;
int MAX_TRANS_TIME;
int DURATION;
int queuecount;
int shortline;
int temp;
cout << "Enter these parameters of the simulation:" << endl;
cout << " The number of queue/server pairs: ";
cin >> queuecount;
Queue line[queuecount];
cout << " The probability that a customer arrives in one tick (%): ";
cin >> ARV_PROB;
cout << " The maximum duration of a transaction in ticks: ";
cin >> MAX_TRANS_TIME;
cout << " The duration of the simulation in ticks: ";
cin >> DURATION;
cout << "Enter a random number seed: ";
cin >> seed;
srand(seed);
for (int time = 0; time < DURATION; ++time)
{
if ( rand() % 100 < ARV_PROB )
{
shortline = shortest_queue(line, queuecount);
line[shortline].enqueue(time);
}
if ( trans_time == 0 )
{
if ( !line.empty() )
{
entry_time = line.dequeue();
temp = (time - entry_time);
if(temp > wait_time)
wait_time = temp;
wait_sum += (time - entry_time);
++count;
trans_time = (rand() % MAX_TRANS_TIME) + 1;
}
}
else
{
--trans_time;
}
cout << setw(4) << time << setw(4) << trans_time << " " << line << endl;
}
cout << count << " customers waited an average of ";
cout << wait_sum / count << " ticks." << endl;
cout << "The longest time a customer waited was " << wait_time << " ticks." << endl;
cout << queue_total(line, queuecount) << " customers remain in the lines." << endl;
return 0;
}
Queue line[queuecount];
if ( !line.empty() )
line is not a Queue. It is an array of Queues, so you have to call empty() on the specific array element you want to check.
Related
I finished this code homework assignment tonight. I thought I was done, but I just realized that my "Average" value is coming out wrong with certain values. For example: When my professor entered the values 22, 66, 45.1, and 88 he got an "Average" of 55.27. However, when I enter those values in my program, I get an "Average" of 55.25. I have no idea what I am doing wrong. I was pretty confident in my program until I noticed that flaw. My program is due at midnight, so I am clueless on how to fix it. Any tips will be greatly appreciated!
Code Prompt: "Write a program that dynamically allocates an array large enough to hold a user-defined number of test scores. Once all the scores are entered, the array should be passed to a function that sorts them in ascending order. Another function should be called that calculates the average score. The program should display the sorted list of scores and averages with appropriate headings. Use pointer notation rather than array notation whenever possible."
Professor Notes: The book only states, "Input Validation: Do not accept negative numbers for test scores." We also need to have input validation for the number of scores. If it is negative, including 0, the program halts, we should consider this situation for 'counter' not to be negative while we have a loop to enter numbers. So negative numbers should be rejected for the number of scores and the values of scores.
Here is my code:
#include <iostream>
#include <iomanip>
using namespace std;
void showArray(double* array, int size);
double averageArray(double* array, int size);
void orderArray(double* array, int size);
int main()
{
double* scores = nullptr;
int counter;
double numberOfScores;
cout << "\nHow many test scores will you enter? ";
cin >> numberOfScores;
if (numberOfScores < 0) {
cout << "The number cannot be negative.\n"
<< "Enter another number: ";
cin >> numberOfScores;
}
if (numberOfScores == 0) {
cout << "You must enter a number greater than zero.\n"
<< "Enter another number: ";
cin >> numberOfScores;
}
scores = new double[numberOfScores];
for (counter = 0; counter < numberOfScores; counter++) {
cout << "Enter test score " << (counter + 1) << ": ";
cin >> *(scores + counter);
if (*(scores + counter) < 0) {
cout << "Negative scores are not allowed. " << endl
<< "Enter another score for this test : ";
cin >> *(scores + counter);
}
}
orderArray(scores, counter);
cout << "\nThe test scores in ascending order, and their average, are: " << endl
<< endl;
cout << " Score" << endl;
cout << " -----" << endl
<< endl;
showArray(scores, counter);
cout << "\nAverage Score: "
<< " " << averageArray(scores, counter) << endl
<< endl;
cout << "Press any key to continue...";
delete[] scores;
scores = nullptr;
system("pause>0");
}
void orderArray(double* array, int size)
{
int counterx;
int minIndex;
int minValue;
for (counterx = 0; counterx < (size - 1); counterx++) {
minIndex = counterx;
minValue = *(array + counterx);
for (int index = counterx + 1; index < size; index++) {
if (*(array + index) < minValue) {
minValue = *(array + index);
minIndex = index;
}
}
*(array + minIndex) = *(array + counterx);
*(array + counterx) = minValue;
}
}
double averageArray(double* array, int size)
{
int x;
double total{};
for (x = 0; x < size; x++) {
total += *(array + x);
}
double average = total / size;
return average;
}
void showArray(double* array, int size)
{
for (int i = 0; i < size; i++) {
cout << " " << *(array + i) << endl;
}
}
I try to start my answers with a brief code review:
#include <iostream>
#include <iomanip>
using namespace std; // Bad practice; avoid
void showArray(double* array, int size);
double averageArray(double* array, int size);
void orderArray(double* array, int size);
int main()
{
double* scores = nullptr;
int counter;
double numberOfScores;
cout << "\nHow many test scores will you enter? ";
cin >> numberOfScores;
// This is not input validation, I can enter two consecutive bad values,
// and the second one will be accepted.
if (numberOfScores < 0) {
// Weird formatting, this blank line
cout << "The number cannot be negative.\n"
<< "Enter another number: ";
cin >> numberOfScores;
}
// The homework, as presented, doesn't say you have to treat 0 differently.
if (numberOfScores == 0) {
cout << "You must enter a number greater than zero.\n"
<< "Enter another number: ";
cin >> numberOfScores;
}
scores = new double[numberOfScores];
// Declare your loop counter in the loop
for (counter = 0; counter < numberOfScores; counter++) {
cout << "Enter test score " << (counter + 1) << ": ";
cin >> *(scores + counter);
if (*(scores + counter) < 0) {
cout << "Negative scores are not allowed. " << endl
<< "Enter another score for this test : ";
cin >> *(scores + counter);
}
}
orderArray(scores, counter); // Why not use numberOfScores?
cout << "\nThe test scores in ascending order, and their average, are: " << endl
<< endl;
cout << " Score" << endl;
cout << " -----" << endl
<< endl;
showArray(scores, counter); // Same as above.
cout << "\nAverage Score: "
<< " " << averageArray(scores, counter) << endl
<< endl;
cout << "Press any key to continue...";
delete[] scores;
scores = nullptr;
system("pause>0"); // Meh, I suppose if you're on VS
}
void orderArray(double* array, int size)
{
int counterx;
int minIndex;
int minValue; // Unnecessary, and also the culprit
// This looks like selection sort
for (counterx = 0; counterx < (size - 1); counterx++) {
minIndex = counterx;
minValue = *(array + counterx);
for (int index = counterx + 1; index < size; index++) {
if (*(array + index) < minValue) {
minValue = *(array + index);
minIndex = index;
}
}
*(array + minIndex) = *(array + counterx);
*(array + counterx) = minValue;
}
}
double averageArray(double* array, int size)
{
int x;
double total{};
for (x = 0; x < size; x++) {
total += *(array + x);
}
double average = total / size;
return average;
}
void showArray(double* array, int size)
{
for (int i = 0; i < size; i++) {
cout << " " << *(array + i) << endl;
}
}
When you are sorting your array, you keep track of the minValue as an int and not a double. That's why your average of the sample input is incorrect. 45.1 is truncated to 45 for your calculations. You don't need to keep track of the minValue at all. Knowing where the minimum is, and where it needs to go is sufficient.
But as I pointed out, there are some other serious problems with your code, namely, your [lack of] input validation. Currently, if I enter two consecutive bad numbers, the second one will be accepted no matter what. You need a loop that will not exit until a good value is entered. It appears that you are allowed to assume that it's always a number at least, and not frisbee or any other non-numeric value.
Below is an example of what your program could look like if your professor decides to teach you C++. It requires that you compile to the C++17 standard. I don't know what compiler you're using, but it appears to be Visual Studio Community. I'm not very familiar with that IDE, but I imagine it's easy enough to set in the project settings.
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
// Assumes a number is always entered
double positive_value_prompt(const std::string& prompt) {
double num;
std::cout << prompt;
do {
std::cin >> num;
if (num <= 0) {
std::cerr << "Value must be positive.\n";
}
} while (num <= 0);
return num;
}
int main() {
// Declare variables when you need them.
double numberOfScores =
positive_value_prompt("How many test scores will you enter? ");
std::vector<double> scores;
for (int counter = 0; counter < numberOfScores; counter++) {
scores.push_back(positive_value_prompt("Enter test score: "));
}
std::sort(scores.begin(), scores.end());
for (const auto& i : scores) {
std::cout << i << ' ';
}
std::cout << '\n';
std::cout << "\nAverage Score: "
<< std::reduce(
scores.begin(), scores.end(), 0.0,
[size = scores.size()](auto mean, const auto& val) mutable {
return mean += val / size;
})
<< '\n';
}
And here's an example of selection sort where you don't have to worry about the minimum value. It requires that you compile to C++20. You can see the code running here.
#include <iostream>
#include <random>
#include <vector>
void selection_sort(std::vector<int>& vec) {
for (int i = 0; i < std::ssize(vec); ++i) {
int minIdx = i;
for (int j = i + 1; j < std::ssize(vec); ++j) {
if (vec[j] < vec[minIdx]) {
minIdx = j;
}
}
int tmp = vec[i];
vec[i] = vec[minIdx];
vec[minIdx] = tmp;
}
}
void print(const std::vector<int>& v) {
for (const auto& i : v) {
std::cout << i << ' ';
}
std::cout << '\n';
}
int main() {
std::mt19937 prng(std::random_device{}());
std::uniform_int_distribution<int> dist(1, 1000);
std::vector<int> v;
for (int i = 0; i < 10; ++i) {
v.push_back(dist(prng));
}
print(v);
selection_sort(v);
print(v);
}
I opted not to give your code the 'light touch' treatment because than I would have done your homework for you, and that's just not something I do. However, the logic shown should still be able to guide you toward a working solution.
I am working on a program in which I have a function and I am hoping to time it. Currently, I considered clock_t in the ctime module to be useful, but when I entered the code for timing, I got (I used Dev-C++ to edit) "permission denied". Below is my code:
#include <iostream>
#include <vector>
#include <ctime>
// Initialization
const int maxN = 99999;
int tokens[maxN] = {}; // All the tokens at mission 1
bool use[maxN] = {}; // Status of the tokens (used or not used)
int bag[maxN]; // Bag to put the tokens into
using namespace std;
int ansIdx = 1; // Answer number
char menu() {
// Print menu
cout << "0: terminate\n";
cout << "1: mission 1 - permutations from 1 ~ N\n";
cout << "2: mission 2 - permutations from input\n";
// Ask for input
cout << "Please input a choice (0 ~ 2): ";
char choice;
cin >> choice;
// Valid command?
if (choice >= '0' and choice <= '2') {
return choice;
}
return '\0';
}
int permutations(int depth, int n, int l) {
if (depth == n) {
// Arranged all elements, so cout each of the elements.
cout << "[" << ansIdx << "] ";
for (int i = 0; i < n; i++) cout << bag[i] << " ";
cout << "\n";
ansIdx++;
return l;
}
for (int i = 0; i < n; i++) {
// Else, for each UNUSED element at this layer:
if (use[i] == 0) {
// Put it into bag[i].
bag[depth] = tokens[i];
// Set the status of it used.
use[i] = 1;
// Call recursion.
permutations(depth + 1, n, l+1);
// Backtrack.
use[i] = 0;
}
}
}
int main() {
// Print menu.
cout << "PERMUTATION GENERATOR\n";
char executionMode;
while (executionMode != '0') {
executionMode = menu();
while (executionMode == '\0') {
executionMode = menu();
}
int layers;
clock_t start;
double ms;
switch (executionMode) {
case '1':
cout << "Enter N: ";
int N;
cin >> N;
for (int i = 0; i < N; i++) {
tokens[i] = i + 1;
}
start = clock();
layers = permutations(0, N, 0);
ms = ((double)(clock() - start)) / CLOCKS_PER_SEC;
cout << "L = " << layers << "\n";
cout << "Mission 1: " << ansIdx - 1 << " permutations\n";
cout << "Used: " << ms << "ms\n";
ansIdx = 1;
break;
case '2':
int M = 0;
while (M < 2 or M > 9) {
cout << "Enter length of input (2 ~ 9): ";
cin >> M;
}
for (int i = 0; i < M; i++) {
cout << "Enter a number: ";
cin >> tokens[i];
}
start = clock();
layers = permutations(0, M, 0);
ms = ((double)(clock() - start)) / CLOCKS_PER_SEC;
cout << "L = " << layers << "\n";
cout << "Mission 2: " << ansIdx - 1 << " permutations\n";
cout << "Used: " << ms << "ms";
ansIdx = 1;
break;
}
}
return 0;
}
Can anyone help me? Any suggestions are appreciated.
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;
Hello i am trying to create a program in which you enter your deals and after you're finished you should get a list of the deals . I want to get them displayed with an array but i keep getting an error must have a pointer to object.
#include <iostream>
using namespace std;
int main() {
int deal;
int date;
int type;
int quantity;
int quality;
int end;
int find;
for (deal = 0; deal < 5000; deal++) {
for (date = 0; date < 5000; date++) {
cout << " enter the year,month,day and hour of pruchase in this format YYYY/MM/DD/HH/MM" << endl;
cin >> date;
for (type = 0; type < 5000; type++) {
cout << " enter the mushroom type. 1 = манатарка, 2 = печурка, 3 = кладница 4 = пачи крак, 5 = съренла, 6 = друг вид гъба "<<endl;
cin >> type;
for (quantity = 0; quantity < 5000; quantity++) {
cout << " enter the mushroom quantity " << endl;
cin >> quantity;
for (quality = 0; quality < 5000; quality++) {
cout << "enter the mushroom quality from 1 to 3 " << endl;
cin >> quality;
cout << "Press 1 for a new deal , press 2 to exit" << endl;
cin >> end;
if (end = 2)
{
deal[date];
goto stop;
}
}
}
}
}
}
stop:
for (find = 0; find < 5000; find++) {
int find = 0;
cout << date[find] << ", " << type[find] << ", " << quantity[find] << ", " << quality[find];
//error must have a pointer to object
}
}
Your date, find, etc. variables are defined as scalars. You cannot refer to them date[find]. You should have declared them as arrays/vectors.
deal should be declared as array type of int.
This seems simple enough but I'm missing something here to make this code work. What I'm trying to do is print the contents of the two dimensional array in 25 rows and 4 columns with student's num, id, score, and name.
I experimented with something similar to this code when I initialized the array with numbers. But now that I'm reading the data from a file, I've hit a wall and need help.
I tried using the name of the array in the cin object but I got an error message like this:
"assign6.cpp:49:11: error: no match for 'operator>>' (operand types are 'std::ifstream {aka std::basic_ifstream}' and 'const int (*)[4]')"
So I took that out and now the code compiles but I get garbage. Any suggestions? Sorry about not getting back soon. I got caught up in other assignments. I made changes and now the programs works. Here the results.
#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
#include <fstream>
using namespace std;
//const
const int Array_Row = 25;
const int Array_Col = 4;
//arrays
string letterGrade[Array_Row];
int myScores[Array_Row][Array_Col];
string names[Array_Row];
int main()
{
int count;
//int average;
ifstream inFile;
inFile.open("classData.txt");
int arraySize = 0;
if(inFile.is_open())
{
int counter = 0;
while(inFile.eof()==false)
{
inFile >> myScores[counter][0];
inFile >> myScores[counter][1];
inFile >> myScores[counter][2];
inFile >> myScores[counter][3];
getline(inFile, names[counter]);
counter++;
}
}else
cout << "Failed";
for(int counter = 0; counter < Array_Row-2; counter++)
{
for(int index = 0; index < Array_Col; index++)
{
cout << setw(4) << fixed;
cout << myScores[counter][index];
}
cout << names[counter] << endl;
}
inFile.close();
for(int counter = 0; counter < Array_Row-2; counter++)
{
cout << setprecision(2) << setw(2) << fixed;
double studentAverage = (myScores[counter][0] + myScores[counter][1] + myScores[counter][2] + myScores[counter][3])/4.0;
cout << "Student average is ";
cout << studentAverage;
cout << " ......" <<names[counter] << endl;
if(studentAverage >=90.00)
letterGrade[counter] = "A";
else if(studentAverage >=80.00 && studentAverage<=89.99)
letterGrade[counter] = "B";
else if(studentAverage >=70.00 && studentAverage<=79.99)
letterGrade[counter] = "C";
else if(studentAverage >=60.00 && studentAverage<=69.99)
letterGrade[counter] = "D";
else if(studentAverage <59)
letterGrade[counter] = "F";
cout << "Student letter grade is: "<< letterGrade[counter] << endl;
}
double classAverage = 0;
for(int counter = 0; counter < Array_Row-2; counter++)
{
classAverage += (myScores[counter][0] + myScores[counter][1] + myScores[counter][2] + myScores[counter][3]);
}
cout << "Class average is : "<< (classAverage/92.0);//calculate class average
int test1Total = 0;
for(int index = 0; index <Array_Row-2; index++)
test1Total += myScores[index][0];
int test1Average = (test1Total/23.0); //calculates test1 average
cout <<"\nStudent average for test 1: " << test1Average << setprecision(2) <<fixed;
int test2Total = 0;
for(int index = 0; index <Array_Row-2; index++)
test2Total += myScores[index][1];
int test2Average = (test2Total/23.0);
cout <<"\nStudent average for test 2: " << test2Average;//calculates test2 average
int test3Total = 0;
for(int index = 0; index <Array_Row-2; index++)
test3Total += myScores[index][2];
int test3Average = (test3Total/23.0);
cout <<"\nStudent average for test 3: " << test3Average;//calculates test3 average
int test4Total = 0;
for(int index = 0; index <Array_Row-2; index++)
test4Total += myScores[index][3];
int test4Average = (test4Total/23.0);
cout <<"\nStudent average for test 4: " << test4Average;//calculates test4 average
return 0;
}
I can't find the error you've posted, but the problem with the code is the getline(...) function.
This is getline's prototype:
istream& getline (istream& is, string& str);
as you can see it returns an istream which you cannot pass to the << operator.
What you can do is:
string str;
getline(inFile, name) >> str;
and then print:
cout << "The numbers are"
<< myArray[count][index]
<< str << endl;
You have an error in this statement
cout << "The numbers are"
<< myArray[count][index]
<< getline(inFile,name) << endl;
Operator >> performed from left to right. So first you output to cout
cout << "The numbers are"
Then you send to cout uninitialized value of myArray[count][index]
<< myArray[count][index]
And after that
<< getline(inFile,name) << endl;
Also, you have an error in using of getline. If your input file contain just space separated int values the right version is
inFile >> myArray[count][index];
cout << "The numbers are"
<< myArray[count][index] << endl;