c++ array showing an error - c++

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.

Related

How can I sort in descending order?

I'm trying to sort for the top and second top value of totalRevenue and its name. I've tried to sort them in descending order this way but I could not figure it out how to make it work. Can anyone please help me out?
First two entries:
1002 Hammer 23.65 203
1024 Nails 6.95 400
Here is the code:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
// Structure to hold statistics
struct Selling {
int productNumber;
string name;
double price;
int soldNumber;
double totalRevenue[];
};
int main()
{
ifstream statFile;
string productName;
double price;
int productNumber, soldNumber;
Selling *productArray[100];
Selling *aSelling;
int numProduct = 0;
int man = 0;
statFile.open("sales.txt");
while (numProduct < 100 && statFile >> productNumber >> productName >> price >> soldNumber)
{
Selling *aSelling = new Selling;
aSelling->productNumber = productNumber;
aSelling->name = productName;
aSelling->price = price;
aSelling->soldNumber = soldNumber;
aSelling->totalRevenue[] = aSelling->price * aSelling->soldNumber;
productArray[numProduct++] = aSelling;
//cout << aSelling->productNumber<< " " << aSelling->name << " " << aSelling->price << " " << aSelling->soldNumber << " " << aSelling->totalRevenue << endl;
}
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (aSelling->totalRevenue[i] > aSelling->totalRevenue[j]) {
man = aSelling->totalRevenue[i];
aSelling->totalRevenue[i] = aSelling->totalRevenue[j];
aSelling->totalRevenue[i] = man;
}
}
}
for (int i = 0; i < 2; i++) {
cout << "The top selling product is " << aSelling->name << "with total sales of " << aSelling->totalRevenue[i] << endl;
cout << "The second top selling product is " << aSelling->name << "with total sales of " << aSelling->totalRevenue[i - 1] << endl;
}
}
And there is an unexpected expression error at the line aSelling->totalRevenue[] = aSelling->price * aSelling->soldNumber; which I don't understand.
There is some confusion on the arrays to sort:
you should define totalRevenue as a double, not an array of doubles,
should be sort the first numProduct elements of the array productArray based on the criteria totalRevenue and name, the order is determined by the comparison operator used. Only compare the second criteria if the first criteria give equal values.
Here is a modified version:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
// Structure to hold statistics
struct Selling {
int productNumber;
string name;
double price;
int soldNumber;
double totalRevenue;
};
int compareSellings(const Selling *a, const Selling *b) {
// sort in decreasing order of totalRevenue
if (a->totalRevenue > b->totalRevenue) return -1; // a comes before b
if (a->totalRevenue < b->totalRevenue) return +1; // b comes before a
// sort in increasing order of name for the same totalRevenue
if (a->name < b->name) return -1; // a comes before b
if (a->name > b->name) return +1; // b comes before a
return 0;
}
int main() {
ifstream statFile;
string productName;
double price;
int productNumber, soldNumber;
Selling *productArray[100];
int numProduct = 0;
statFile.open("sales.txt");
while (numProduct < 100 && statFile >> productNumber >> productName >> price >> soldNumber) {
Selling *aSelling = new Selling;
aSelling->productNumber = productNumber;
aSelling->name = productName;
aSelling->price = price;
aSelling->soldNumber = soldNumber;
aSelling->totalRevenue = price * soldNumber;
productArray[numProduct++] = aSelling;
//cout << aSelling->productNumber<< " " << aSelling->name << " "
// << aSelling->price << " " << aSelling->soldNumber << " "
// << aSelling->totalRevenue << endl;
}
for (int i = 0; i < numProduct; i++) {
for (int j = 0; j < numProduct; j++) {
if (compareSellings(productArray[i], productArray[j]) > 0) {
Selling *aSelling = productArray[i];
productArray[i] = productArray[j];
productArray[j] = aSelling;
}
}
}
cout << "The top selling product is " << productArray[0]->name
<< ", with total sales of " << productArray[0]->totalRevenue << endl;
cout << "The second selling product is " << productArray[1]->name
<< ", with total sales of " << productArray[1]->totalRevenue << endl;
return 0;
}
Further remarks:
you might use a more efficient sorting method
you should free the allocated objects
you should use <algorithms> and dynamic arrays of objects instead of allocating the objects with new and manipulating naked pointers.
you should handle exceptions

Adding conditions to a conditional statement

I am messing around with dynamic arrays for a user defined amount of inputs for an and gate.
The issue I am running into is that I don't know how many inputs the user is going to test and I need to be able to have an if-else statement that tests each input.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
class logic_gate {
public:
int x = 0;
};
int main() {
int userInput = 0;
cout << "How many inputs do you want on your and gate?: ";
cin >> userInput;
cout << endl;
logic_gate *and_gate = new logic_gate[userInput];
cout << endl << "Please enter the values of each bit below . . ." << endl <<
endl;
int userTest1 = 0;
for (int i = 0; i < userInput; i++) {
cout << "#" << i + 1 << ": ";
cin >> userTest1;
and_gate[i].x = userTest1;
}
return 0;
}
Here is the code that I am currently trying to find a solution for.
To implement an AND gate with n inputs you can simply do:
int output = 1;
for (int i = 0; i < n; ++i)
{
if (!and_gate [i])
{
output = 0;
break;
}
}
// ...
Use Vector data structure, you don't need to tell its size while declaring, unlike array, and it can grow automatically.
To read input till it's arriving, put cin inside while loop condition. I used getline to read whole line and work with it, so that whenever user presses enter button at empty line, program will think that no more input is coming anymore, and will start calculating 'And' of inputs.
//don't forget to import vector
#include <iostream>
#include <vector>
#include <string>
using namespace std;
class logic_gate {
public:
int x = 0;
logic_gate(){ //default constructor
}
logic_gate(int k){ //another constructor needed
x = k;
}
};
int main(){
cout << endl << "Please enter the values of each bit below . . ." << endl;
vector<logic_gate> and_gate; //no need to tell size while declaration
string b;
while(getline(cin, b)){ //read whole line from standard input
if (b == "\0") //input is NULL
break;
and_gate.push_back(logic_gate(stoi(b))); //to convert string to integer
}
if (!and_gate.empty()){
int output = and_gate[0].x;
for (int i = 1; i < and_gate.size(); i++){
output = output & and_gate[i].x;
}
cout << "And of inputs is: " << output << endl;
}
else{
cout << "No input was given!\n";
}
return 0;
}
Feel free to ask if some doubts linger
I figured out what I wanted to do. Thanks to everyone who helped and especially Paul Sanders. Below is my final code.
#include <iostream>
using namespace std;
class logic_gate {
public:
int x = 0;
};
int main() {
int userInput;
int output = 1;
cout << "How many inputs do you want on your and gate?: ";
cin >> userInput;
cout << endl;
logic_gate *and_gate = new logic_gate[userInput];
cout << endl << "Please enter the values of each bit below . . ." << endl <<
endl;
int userTest1;
for (int i = 0; i < userInput; i++) {
cout << "#" << i + 1 << ": ";
cin >> userTest1;
and_gate[i].x = userTest1;
}
if (userInput == 1) {
output = userTest1;
cout << "The test of " << userTest1 << " is " << output << endl << endl;
}
else if (userInput > 1) {
for (int i = 0; i < userInput; i++) {
if (!and_gate[i].x)
{
output = 0;
break;
}
}
cout << "The test of ";
for (int i = 0; i < userInput; i++) {
cout << and_gate[i].x;
}
cout << " is " << output << endl << endl;
}
return 0;
}

Need help on getting the smallest three numbers on an array

For this program a user must enter 10 contestants and the amount of second it took for them to complete a swimming race. My problem is that I must output the 1st, 2nd and 3rd placers, so I need to get the three smallest arrays (as they would be the quickest times) but I'm unsure on how to do it. Here is my code so far.
string names[10] = {};
int times[10] = { 0 };
int num[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int min1 = 0, min2 = 0, min3 = 0;
cout << "\n\n\tCrawl";
for (int i = 0; i < 10; i++)
{
cout << "\n\n\tPlease enter the name of contestant number " << num[i] << ": ";
cin >> names[i];
cout << "\n\tPlease enter the time it took for them to complete the Crawl style: ";
cin >> times[i];
while (!cin)
{
cout << "\n\tError! Please enter a valid time: ";
cin.clear();
cin.ignore();
cin >> times[i];
}
if (times[i] < times[min1])
min1 = i;
cout << "\n\n\t----------------------------------------------------------------------";
}
system("cls");
cout << "\n\n\tThe top three winners of the Crawl style race are as follows";
cout << "\n\n\t1st Place - " << names[min1];
cout << "\n\n\t2nd Place - " << names[min2];
cout << "\n\n\t3rd Place - " << names[min3];
}
_getch();
return 0;
}
As you can see, it is incomplete. I know how to get the smallest number, but its the second and third smallest that is giving me trouble.
your code is full of errors:
what do you do with min2 and min3 as long as you don't assign them?? they are always 0
try checking: cout << min2 << " " << min3;
also you don't initialize an array of strings like that.
why you use an array of integers for just printing number of input:
num? instead you can use i inside loop adding to it 1 each time
to solve your problem use a good way so consider using structs/clusses:
struct Athlete
{
std::string name;
int time;
};
int main()
{
Athlete theAthletes[10];
for(int i(0); i < 10; i++)
{
std::cout << "name: ";
std::getline(std::cin, theAthletes[i].name);
std::cin.sync(); // flushing the input buffer
std::cout << "time: ";
std::cin >> theAthletes[i].time;
std::cin.sync(); // flushing the input buffer
}
// sorting athletes by smaller time
for(i = 0; i < 10; i++)
for(int j(i + 1); j < 10; j++)
if(theAthletes[i].time > theAthletes[j].time)
{
Athlete tmp = theAthletes[i];
theAthletes[i] = theAthletes[j];
theAthletes[j] = tmp;
}
// printing the first three athletes
std::cout << "the first three athelets:\n\n";
std::cout << theAthletes[0].name << " : " << theAthletes[0].time << std::endl;
std::cout << theAthletes[1].name << " : " << theAthletes[1].time << std::endl;
std::cout << theAthletes[2].name << " : " << theAthletes[2].time << std::endl;
return 0;
}
I hope this will give u the expected output. But i suggest u to use some sorting alogirthms like bubble sort,quick sort etc.
#include <iostream>
#include<string>
using namespace std;
int main() {
int times[10] = { 0 };
int num[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int min1 = 0, min2 = 0, min3 = 0,m;
string names[10] ;
cout << "\n\n\tCrawl";
for (int i = 0; i < 10; i++)
{
cout << "\n\n\tPlease enter the name of contestant number " << num[i] << ": ";
cin >> names[i];
cout << names[i];
cout << "\n\tPlease enter the time it took for them to complete the Crawl style: ";
cin >> times[i];
cout<<times[i];
while (!cin)
{
cout << "\n\tError! Please enter a valid time: ";
cin.clear();
cin.ignore();
cin >> times[i];
}
if(times[i]==times[min1]){
if(times[min1]==times[min2]){
min3=i;
}else{min2 =i;}
}else if(times[i]==times[min2]){
min3=i;
}
if (times[i] < times[min1]){
min1 = i;
cout <<i;
}
int j=0;
while(j<i){
if((times[j]>times[min1])&&(times[j]<times[min2])){
min2 =j;
j++;
}
j++;
}
m=0;
while(m<i){
if((times[m]>times[min2])&&(times[m]<times[min3])){
min3 =m;
m++;
}
m++;
}
cout << "\n\n\t----------------------------------------------------------------------";
}
cout << "\n\n\tThe top three winners of the Crawl style race are as follows";
cout << "\n\n\t1st Place - " << names[min1];
cout << "\n\n\t2nd Place - " << names[min2];
cout << "\n\n\t3rd Place - " << names[min3];
return 0;
}
There is actually an algorithm in the standard library that does exactly what you need: std::partial_sort. Like others have pointed out before, to use it you need to put all the participant data into a single struct, though.
So start by defining a struct that contains all relevant data. Since it seems to me that you only use the number of the contestants in order to be able to later find the name to the swimmer with the fastest time, I'd get rid of it. Of course you could also add it back in if you like.
struct Swimmer {
int time;
std::string name;
};
Since you know that there always will be exactly 10 participants in a race, you can also go ahead and replace the C-style array by a std::array.
The code to read in the users then could look like this:
std::array<Swimmer, 10> participants;
for (auto& participant : participants) {
std::cout << "\n\n\tPlease enter the name of the next contestant: ";
std::cin >> participant.name;
std::cout << "\n\tPlease enter the time it took for them to complete the Crawl style: ";
while(true) {
if (std::cin >> participant.time) {
break;
}
std::cout << "\n\tError! Please enter a valid time: ";
std::cin.clear();
std::cin.ignore();
}
std::cout << "\n\n\t----------------------------------------------------------------------";
}
Partial sorting is now essentially a one-liner:
std::partial_sort(std::begin(participants),
std::begin(participants) + 3,
std::end(participants),
[] (auto const& p1, auto const& p2) { return p1.time < p2.time; });
Finally you can simply output the names of the first three participants in the array:
std::cout << "\n\n\tThe top three winners of the Crawl style race are as follows";
std::cout << "\n\n\t1st Place - " << participants[0].name;
std::cout << "\n\n\t2nd Place - " << participants[1].name;
std::cout << "\n\n\t3rd Place - " << participants[2].name << std::endl;
The full working code can be found on coliru.
This is not a full solution to your problem, but just meant to point you into the right direction...
#include <iostream>
#include <limits>
#include <algorithm>
using namespace std;
template <int N>
struct RememberNsmallest {
int a[N];
RememberNsmallest() { std::fill_n(a,N,std::numeric_limits<int>::max()); }
void operator()(int x){
int smallerThan = -1;
for (int i=0;i<N;i++){
if (x < a[i]) { smallerThan = i; break;}
}
if (smallerThan == -1) return;
for (int i=N-1;i>smallerThan;i--){ a[i] = a[i-1]; }
a[smallerThan] = x;
}
};
int main() {
int a[] = { 3, 5, 123, 0 ,-123, 1000};
RememberNsmallest<3> rns;
rns = std::for_each(a,a+6,rns);
std::cout << rns.a[0] << " " << rns.a[1] << " " << rns.a[2] << std::endl;
// your code goes here
return 0;
}
This will print
-123 0 3
As you need to know also the names for the best times, you should use a
struct TimeAndName {
int time;
std::string name;
}
And change the above functor to take a TimeAndName instead of the int and make it also remember the names... or come up with a different solution ;), but in any case you should use a struct similar to TimeAndName.
As your array is rather small, you could even consider to use a std::vector<TimeAndName> and sort it via std::sort by using your custom TimeAndName::operator<.

C++ Queue Simulation

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.

Entering data from .txt into struct array

For my c++ homework, I have an .txt document containing building information ordered like:
Building name
year built
lat coordinate
lon coordinate
ex.
Parking Deck
1993
34.2252
37.5563
Admin Building
1985
34.2356
37.5734
I have to read this into an array of my created struct:
struct list
{
char name[50];
int yearBuilt;
double latCoord;
double lonCoord;
} building;
now I've created a for loop to read in the data to my created array of type list:
list buildingnumber[SIZE]; //array for buildings
But when I try to print out the "k" earliest buildings made, it shows no data in the array
Here's my current code:
#include <iostream>
#include <fstream>
#include <istream>
#include <cstdlib>
#include <string>
using namespace std;
const int SIZE = 5000;
//struct for building type
struct list
{
char name[50];
int yearBuilt;
double latCoord;
double lonCoord;
}building;
list buildingnumber[SIZE]; //array for buildings
void InsertionSort(list buildingnumber[], int buildingsloaded)
{
int key = 0, i = 0;
for(int j = 1; j < buildingsloaded; j++)
{
key=buildingnumber[j].yearBuilt;
i=j-1;
while(buildingnumber[i].yearBuilt > key && i >= 0)
{
buildingnumber[i+1] = buildingnumber[i];
i--;
}
buildingnumber[i+1].yearBuilt = key;
}
}
int main()
{
char filePath[50];
ifstream openFile;
cout << "Enter the path of the building file: ";
cin.getline(filePath, 50);
openFile.open(filePath);
//verify if file is opened + report buildings loaded
int buildingsloaded = 0;
if(!openFile.fail())
{
while(openFile >> building.name >> building.yearBuilt >> building.latCoord >> building.lonCoord)
{
buildingsloaded++;
}
cout << buildingsloaded << " buildings have been loaded." << endl;
}
// get how many buildings user wants
int k = 0;
cout << "How many buildings are you interested in?: ";
cin >> k;
//create array
// loadKbuildings(building, buildingsloaded);
for(int i = 0; i < k; i++)
{
openFile >> buildingnumber[i].name >> buildingnumber[i].yearBuilt >> buildingnumber[i].latCoord >> buildingnumber[i].lonCoord;
}
// insertion sort
InsertionSort(buildingnumber, buildingsloaded);
// display earliest k buildings
cout << "The " << k << " oldest buildings are: " << endl;
int i = 0;
while ( i < k )
{
cout << buildingnumber[i].name << endl;
cout << "Year Built: " << buildingnumber[i].yearBuilt << endl;
cout << "Coordinates: (" << buildingnumber[i].latCoord << "," << buildingnumber[i].lonCoord << ")" << endl;
cout << endl;
i++;
}
}
The problem is here:
if(!openFile.fail())
{
while(openFile >> building.name >> building.yearBuilt >> building.latCoord >> building.lonCoord)
{
buildingsloaded++;
}
cout << buildingsloaded << " buildings have been loaded." << endl;
}
You've read all of the data already (to count the number of buildings); the next time you try to grab the data, it's gone.
You can resolve this issue by storing the buildings in an array the first scan through.
int c = 0;
if(!openFile.fail())
{
// *
while(openFile >> buildingnumber[c].name >> buildingnumber[c].yearBuilt >> buildingnumber[c].latCoord >> buildingnumber[c].lonCoord)
{
buildingsloaded++;
c++;
}
cout << buildingsloaded << " buildings have been loaded." << endl;
}
As per WhozCraig's comment, the line under the star only reads in one word for the building's name; you should use cin.getline() instead and change around the loop condition.
You should obviously also take out the data reading section below:
//create array
// loadKbuildings(building, buildingsloaded);
for(int i = 0; i < k; i++)
{
openFile >> buildingnumber[i].name >> buildingnumber[i].yearBuilt >> buildingnumber[i].latCoord >> buildingnumber[i].lonCoord;
}