#include <iostream>
#include <string>
#include <sstream>
using namespace std;
string getItemName(int k) {
if(k == 0) {
return "Sunkist Orange";
} else if(k == 1) {
return "Strawberry";
} else if(k == 2) {
return "papaya";
} else if(k == 3) {
return "Star Fruit";
} else if(k == 4) {
return "Kiwi";
}
return "";
}
int main() {
double prices[] = {2.00, 22.00, 5.00, 6.00, 10.00};
double total = 0.0;
string cart[50];
int key = 0;
int weight = 0;
int index = 0;
cout << "Welcome to Only Fresh Fruit Shop\n\nToday's fresh fruit <Price per Kg>\n";
cout << "0-Sunkist Orange RM2\n";
cout << "1-Strawberry RM22\n";
cout << "2-Papaya RM5\n";
cout << "3-Star Fruit RM6\n";
cout << "4-Kiwi RM10\n";
while (key != -1) {
double current = 0.0;
cout << "Enter fruit code <-1 to stop>: " << endl;
cin >> key;
if (key == -1) {
break;
}
cout << getItemName(key) << endl;
cout << "Enter weight <kg> : " << endl;
cin >> weight;
current = prices[key] + weight;
total = total + current;
}
cout << "-------------------------------------------------------\nReciept\n";
for(int i = 0; i < index; i++) {
cout << cart[i] << "\n";
}
cout << "TOTAL = RM" << total << endl;
return 0;
}
This is my code so far. The system have to display what fruit the user have chosen at in the receipt. My code is not working on the receipt part. Is there any other way on how to improvise the code to make it simpler? How can I improvise?
At very first you can re-organise your data better:
struct Product
{
std::string name;
double price;
};
This struct keeps the data closely related to a single product (fruit in this case) together locally.
You might organise these in an array (preferrably std::array, alternatively raw) making access to simpler – making your getItemName function obsolete entirely. Instead of a static array a std::vector would allow to manage your products dynamically (adding new ones, removing obsolete ones, ...).
You can even use this array to output your data (and here note that your condition in the while loop is redundant; if the inner check catches, the outer one cannot any more as you break before; if the inner one doesn't, the outer one won't either, so prefer a – seeming – endless loop):
std::vector<Product> products({ {"Apple", 2.0 }, { "Orange", 3.0 } });
for(;;)
{
std::cout << "Welcome ... \n";
for(auto i = products.begin(); i != products.end(); ++i)
{
std::cout << i - products.begin() << " - " << i->name
<< " RM " << i-> price << '\n';
}
// getting key, exiting on -1
if(0 <= key && key < products.size()
{
// only now get weight!
}
else
{
std::cout << "error: invalid product number" << std::endl;
}
}
Now for your cart you might just add indices into the vector or pointers to products – note, though, that these will invalidate if you modify the vector in the mean-time – if you do so you need to consider ways to correctly update the cart as well – alternatively you might just empty it. Inconvenient for the user, but easy to implement…
In any case, such a vector of pointers to products would easily allow to add arbitrary number of elements, not only 50 (at least as much as your hardware's memory can hold...) and would allow for simple deletion as well.
Calculating the full price then might occur only after the user has completed the cart:
// a map allows to hold the weights at the same time...
std::map<Product*, weight> cart;
for(;;)
{
// ...
if(0 <= key && key < products.size()
{
double weight;
std::cin >> weight;
// TODO: check for negative input!
// (always count with the dumbness of the user...)
cart[&products[key]] += weight;
// note: map's operator[] adds a new entry automatically,
// if not existing
}
}
Finally you might iterate over the cart, printing some information and calculating total price for the shopping cart:
double total = 0.0;
for(auto& entry : cart) // value type of a map always is a std::pair
{
std::cout << entry.first->name << "..." << entry.second << " kg\n";
total += entry.first->price * entry.second;
// note: you need MULTIPLICATION here, not
// addition as in your code!
}
std::cout << "Total price: RM " << total << std::endl;
This should do it whilst staying close to original code, I also improved you're method of gathering price/name a bit, try to catch the out of index exceptions or check if current index is NULL. Good luck!
#include <iostream>
#include <string>
#include <sstream>
#include <vector>;
using namespace std;
std::vector<std::string> itemList = {"Sunkist Orange", "Strawberry", "Papaya", "Star Fruit", "Kiwi"};
//If you dont want this to be global put it in the getItemName function
string getItemName(int k) {
return itemList.at(k);
}
int main() {
std::vector<double> prices = { 2.00, 22.00, 5.00, 6.00, 10.00 };
double total = 0.0;
int key = 0, weight = 0;
cout << "Welcome to Only Fresh Fruit Shop\n\nToday's fresh fruit <Price per Kg>\n";
cout << "0-Sunkist Orange RM2\n";
cout << "1-Strawberry RM22\n";
cout << "2-Papaya RM5\n";
cout << "3-Star Fruit RM6\n";
cout << "4-Kiwi RM10\n";
while (key != -1) {
double current = 0.0;
cout << "Enter fruit code <-1 to stop>: " << endl;
cin >> key;
if (key == -1) {
break;
}
cout << getItemName(key) << endl;
cout << "Enter weight <kg> : " << endl;
cin >> weight;
current += prices.at(key) + weight;
total += total + current;
cout << "-------------------------------------------------------\nReciept\n";
cout << "Purchased: " << getItemName(key) <<" "<< "TOTAL = RM" << total << "\n" << endl;
}
return 0;
}
I noticed there is a string cart[50] and int index = 0which you did not use throuoght the whole code except printing it at the end of the code. I am guessing that you want to add the fruit into the cart but it seems like you have not done so.
double price[50];
while (key != -1) {
double current = 0.0;
cout << "Enter fruit code (<-1> to stop): ";
cin >> key;
if (key == -1) break;
cout << getItemName(key) << endl;
cout << "Enter weight <kg> : ";
cin >> weight;
cart[index] = getItemName(key);
price[index] = prices[key] * weight;
total += price[index];
index++;
}
for (int i = 0; i < index; i++) {
cout << cart[i] << " " << price[i] << endl;
}
I have added some code so that cart[index] = getItemName(key). When you print each element of cart, it will now work. Also, current = prices[key] * weight is the correct one, not addition (unless your rules are different).
on a side note are you malaysian
I am trying to make a game selector that you put in your items and it will spit back out a random item. The final functionality of this program is that you can say how many items you want to be selected. I have the random selector working fine but I can't figure out how to change how many items to select. When I try and run this code it will print out the same item the amount of times selected. I want it to do different items. Here is my code so far:
/* Me
6-14-22
Game Selector
*/
#include <iostream>
#include <avector>
#include <random>
using namespace std;
int generated;
vector<string> gameList;
bool going = true;
string usrInp = "";
int gamesCount = 0;
int input() {
while(going){
cout << "Please enter your Items:" << endl;
getline(cin, usrInp);
cout << endl;
if(usrInp == "Done" || usrInp == "done"){
going = false;
return 0;
}
gameList.push_back(usrInp);
}
}
void pickGame() {
srand(time(0));
generated = (rand() % gameList.size());
cout << endl;
cout << gameList[generated] << endl;
}
void gamesNumber(){
cout << "Please enter the amount of games you want :" << endl;
cin >> gamesCount;
int t = 0;
while(t<=gamesCount){
if(t == gamesCount){
pickGame();
t++;
}
else{
t++;
}
}
}
/*
cin gamesCount
pick the amount of games that are in the int of gamesCount
*/
int main() {
input();
gamesNumber();
//gamesNumber();
//gameList.push_back("Minecraft");
//gameList.push_back("Film mac up");
//gameList.push_back("Raft");
//gameList.push_back("Roblox");
//gameList.push_back("Forza Horizon 4");
return 0;
}
Your game picking function looks fine, but the gamesNumber() function is kind of weird.
From what I understood, you want to pick gamesCount games. So you just need to call the pickGame function gamesCount times. Meaning that you can just use a for loop:
void gamesNumber(){
cout << "Please enter the amount of games you want :" << endl;
cin >> gamesCount;
for(int i = 0; i < gamesCount; i++) pickGame();
}
Im starting a project with some friends and we have this problem in our inventory system. We're a bit new in c++ and we've been trying to understand the mistake for a little while but still cant find the problem thx in advance.
The probleme seems to be when I used vector.
For some reason once vector is used I get syntax error in the Inventory part and Equip Part.
Sorry if theres grammar error english is'nt my first language
// inventorySysteme.cpp : This file contains the 'main' function. Program execution begins and ends there.
#include <iostream>
#include <vector>
#include <string>
#include <Windows.h>
using namespace std;
struct Item{
string name; // le nom
string purpose; // weapon, armor
int stats; // Dammage, armor point
int attribute; // 0 = rien 1 = armor pearcing 2 = magic dammage ECt.....
};
int main()
{
Item Sword{
"RustedSword", // nom
"Weapon", // weapon
10, // 10 de dammage
1 // armor pearcing
};
Item Staff{
"FirerStaff",
"Weapon",
20,
2
};
string input; // What the player insert
vector<string> Equipment = { "Empty", "Empty", "Empty", "Empty", "Empty", }; // If the place is free
string InventorySlots[] = { "Weapon", "Weapon", "Objec1", "Object2", "Object3" }; // Nom et place inventaire
vector<Item> Inventory = { Sword, Staff }; // inventaire
while (true) {
cin >> input;
if (input == "equipment") {
for (int i = 0; i < 5; i++) {
cout << InventorySlots[i];
if (Equipment[i] == "Empty") {
cout << " " << Equipment[i] << "\n\n";
}
}
}
// Equip Part
if (input == "equip") {
cout << "What would you like to equip?\n";
cin >> input;
for (int i = 0; i < Inventory.size(); i++) {
//Search for item player want to equip and equip it in the right place.
if (input == Inventory[i].name) {
Equipment[Inventory[i].purpose] = Inventory[i].name;
cout << "Successfully equiped!" << endl;
}
}
}
// Inventory Part
if (input == "inventory") {
for (int i = 0; i < Inventory.size(); i++) {
cout << "________________________________________" << endl;
cout << "| " << Inventory[i] << endl;
cout << "| Carried items " << Inventory.size() << " / " << 10 << endl;
cout << "|_______________________________________" << endl;
}
}
if (input == "quit") {
return 0;
}
}
}
I've been assigned by school to create an application that contains a book list with 20 different books in it and build a menu with following options:
(a) List – Display the list in tabular format. Each display should contain an appropriate heading and column captions;
(b) Search – Search for a book record in the list using the ISBN and print the full record for the book;
(c) Delete – Delete an existing book record from the list;
(d) Exit – Stop the program.
Here is the sample of my program:
#include <iostream>
#include <iomanip>
#include <fstream>
#include <cstring>
#include <cctype>
using namespace std;
typedef struct
{
char code[50];
char author[50];
char name[50];
char edition[50];
char publish[50];
char price[50];
} BOOK_LIST;
void list (BOOK_LIST book[], int rows);
void showBook (BOOK_LIST book[], int rows);
void updateRecord (BOOK_LIST book[], int rows);
void advancedSearch (BOOK_LIST book[], int rows);
int deleteBook (BOOK_LIST book[], int rows);
int searchBook(BOOK_LIST book[], int rows);
int main()
{
ifstream inFile("list.txt");
if(!inFile)
cout << "Error opening input file\n";
else
{
BOOK_LIST books[50];
int index = -1, choice;
inFile.getline(books[++index].code, 50);
while(inFile)
{
if(inFile.peek() == '\n')
inFile.ignore(256, '\n');
inFile.getline(books[index].author, 50);
inFile.getline(books[index].name, 50);
inFile.getline(books[index].edition, 50);
inFile.getline(books[index].publish, 50);
inFile >> books[index].price;
// read next number
inFile >> books[++index].code;
}
inFile.close();
// menu starts
do
{
cout << "Do you want to:\n";
cout << "1. List all books\n";
cout << "2. Get details about a book\n";
cout << "3. Delete a book from the list\n";
cout << "4. Exit\n";
cout << "5. Advanced Search\n";
cout << "Enter choice: ";
cin >> choice;
switch (choice)
{
case 1 : list(books, index);
break;
case 2 : showBook(books, index);
break;
case 3 : updateRecord(books, index);
break;
case 5 : advancedSearch(books, index);
case 4 : break;
default: cout << "Invalid choice\n";
}
} while (choice != 4);
ofstream outFile("list.txt");
if(!outFile)
cout << "Error opening output file, records are not updated.\n";
else
{
for (int i = 0; i < index; i++)
{
outFile << books[i].code << endl;
outFile << books[i].author << endl;
outFile << books[i].name << endl;
outFile << books[i].edition << endl;
outFile << books[i].publish << endl;
outFile << books[i].price << endl;
}
outFile.close();
}
}
return 0;
}
void list(BOOK_LIST book[], int rows)
{
cout << fixed << setprecision(2);
cout << "ISBN\t Author BookName Edition\tPublisher\t Price\n";
for (int i = 0; i < rows; i++)
cout << book[i].code << "\t" << book[i].author << "\t"
<< book[i].name << "\t" << book[i].edition << "\t"
<< book[i].publish << "\t"
<< " " << book[i].price << endl;
return;
}
int searchBook(BOOK_LIST book[], int rows)
{
int i = 0;
bool found = false;
char code[50];
cout << "Enter an ISBN code of a book to search: ";
fflush(stdin);
cin.getline(code, 50);
while (i < rows && !found)
{
if (strcmp(code, book[i].code) == 0)
found = true;
else
i++;
}
if (found)
return i;
else
return -1;
}
void showBook(BOOK_LIST book[], int rows)
{
int pos = searchBook(book, rows);
if (pos != -1)
{
cout << "Author is " << book[pos].author << endl;
cout << "Book name is "<< book[pos].name << endl;
cout << book[pos].edition << " Edition" << endl;
cout << "The publisher of this book is " << book[pos].publish << endl;
cout << "Current price is " << book[pos].price << endl;
}
else
cout << "Product not found\n";
return;
}
void updateRecord(BOOK_LIST book[], int rows)
{
int pos = deleteBook(book, rows);
char code [50];
int i,j = 0;
for(i = 0; i < rows ; i++)
{
if(strcmp(code, book[i].code))
{
strcpy(book[j].code , book[i].code);
strcpy(book[j].author, book[i].author);
strcpy(book[j].name, book[i].name);
strcpy(book[j].edition, book[i].edition);
strcpy(book[j].publish, book[i].publish);
strcpy(book[j].price, book[i].price);
j++;
}//if
else
{
i++;
strcpy(book[j].code, book[i].code);
strcpy(book[j].author, book[i].author);
strcpy(book[j].name, book[i].name);
strcpy(book[j].edition, book[i].edition);
strcpy(book[j].publish, book[i].publish);
strcpy(book[j].price, book[i].price);
j++;
}//else
}//for
return;
}
int deleteBook (BOOK_LIST book[], int rows)
{
int i = 0;
bool found = false;
char code[50];
cout << "Enter an ISBN code of a book to delete: ";
fflush(stdin);
cin.getline(code, 50);
while (i < rows && !found)
{
if (strcmp(code, book[i].code) == 0)
found = true;
else
i++;
}
if (found)
return i;
else
return -1;
}
void advancedSearch (BOOK_LIST book[], int rows)
{
char advanced[50];
cout << "Please enter either the author's name or the book name to search: ";
fflush(stdin);
cin.getline(advanced, 50);
for(int i = 0; i < rows; i++)
{
if(strstr(book[i].author, advanced) || strstr(book[i].name, advanced))
{
cout << "ISBN is " << book[i].code << endl;
cout << "Author is " << book[i].author << endl;
cout << "Book name is " << book[i].name << endl;
cout << book[i].edition << " Edition" << endl;
cout << "Publisher is " << book[i].publish << endl;
cout << "Current price is " << book[i].price << endl;
}
}
return ;
}
The problem starts here:
When I want to permanently delete a whole row of book record. But the book record is still there after deleting.
First, this is my menu, then I press 1 to check the list for the IBSN. Then, I press 3 to proceed to the deleting part. At that time, I choose TheHost to delete. After the deleting, to ensure that I have deleted the chosen book, so I press 1 to check the list again, but unfortunately the book is still there:
If I am able to delete a book record, and how do I delete a record permanently? And after deleting a record, how do I move the remaining records upwards, so that it won't leave any empty row there?
The function for the deleting:
void updateRecord(BOOK_LIST book[], int rows)
{
int pos = deleteBook(book, rows);
char code [50];
int i,j = 0;
for(i = 0; i < rows ; i++)
{
if(strcmp(code, book[i].code))
{
strcpy(book[j].code , book[i].code);
strcpy(book[j].author, book[i].author);
strcpy(book[j].name, book[i].name);
strcpy(book[j].edition, book[i].edition);
strcpy(book[j].publish, book[i].publish);
strcpy(book[j].price, book[i].price);
j++;
}//if
else
{
i++;
strcpy(book[j].code, book[i].code);
strcpy(book[j].author, book[i].author);
strcpy(book[j].name, book[i].name);
strcpy(book[j].edition, book[i].edition);
strcpy(book[j].publish, book[i].publish);
strcpy(book[j].price, book[i].price);
j++;
}//else
}//for
return;
}
The Text file that I used in this program a.k.a the BOOK_LIST
I see (at least) two problems with your code around deleting a book.
in update_record you're using a char code[50] which is being used to compare with strcmp later on but is not initialized.
when you delete a book you should update your index which becomes rows in the update_record method. However index is passed to rows by value which means that even if you try running --rows; in update_record it won't decrement index. You'll need to pass it by reference for it to update index.
On a side note, I agree with comments regarding fixing your code to use vectors/maps & strings instead of simple arrays and char*.
But since you mentioned it was a school task I would guess you haven't reached that sort of material yet.
Good Luck.
The assignment most probably expects you to use std::list template rather than the classical C array. Insertion and deletion is natural for lists.
An alternative would be to use std:map using the ISBN as a key. ISBN is supposed to be globally unique.
Just to expand on my comment, here is one way to remove an element from an array.
Suppose we have an array of char called X, containing {'a', 'b', 'c', 'd', 'e', 'f'}, and we want to get rid of 'c'.
If we want to maintain the order of the remaining elements, then what we're aiming for is {'a', 'b', 'd', 'e', 'f'}. So we copy the 'd' into the 'c' place, the 'e' into the old 'd' place, and so on:
a b c d e f
a b d d e f
a b d e e f
a b d e f f
We can do this with code like
for(int k=2; k<5; ++k)
X[k] = X[k+1];
And what happens to that extra 'f' at the end? We could write some placeholder into that unwanted space, and then watch out for that placeholder for the rest of the run. Or, we could just stop using that space, and say that from now on we're considering an array of length 5. That extra 'f' will still be there, but for now we don't care about what exists past the end of our array.
(If we don't care about the order of the remaining elements, then we can make this a lot simpler.)
Remember, it's always easier to develop new functionality in isolation.
Once you have this working, you can apply it in your code and get a passing grade, but if you really want to learn something useful you should write a Book class.
I'm learning C++ and I'm trying to figure out a method that involves switching out a card in the list below.
for example:
ace of spades
king of hearts
four of clubs
two of hearts
two of clubs
How would I go about exchanging 2, 3, and 5 each for a new card.
Ok so here is my code, i have other header files that it also uses but I think that you guys should be able to understand stand where I going with it.
#ifndef POKERGAME_H
#define POKERGAME_H//guard code
#include <iostream>
#include <iomanip>
//don't need to add .cpp files
#include "Card.h"
#include "Deck.h"
#include "Hand.h"
class PokerGame
{
public:
void playGame()
{
PokerGame play;
Deck myCard;
Hand hand;
Hand list;
cout << "***Simple 5-card Poker***" << endl;
//get a brand new card and places it in position
hand.setCard(0, myCard.getNextCard());
hand.setCard(1, myCard.getNextCard());
hand.setCard(2, myCard.getNextCard());
hand.setCard(3, myCard.getNextCard());
hand.setCard(4, myCard.getNextCard());
cout << "The cards have been shuffled and you are dealt " << endl
<<"1."<< hand.getCard(0).printName() << endl//then i ask what is the name of the card in that position
<<"2."<< hand.getCard(1).printName() << endl
<<"3."<< hand.getCard(2).printName() << endl
<<"4."<< hand.getCard(3).printName() << endl
<<"5."<< hand.getCard(4).printName() << endl;
//ask for users input and store them in an array
int stop = 0;
int user_input[6];
int counter = 0;
while((stop != -1) && counter < 6 )
{
cout << "Indicate the cards that you would like to exchange (-1 to end): ";
cin >> user_input[counter];
if(user_input[counter] > 5 || user_input[counter] < 0 || user_input[counter - 1] == user_input[counter])
{
cout << "Invalid input" << endl;
if(user_input[counter] == -1)
{
stop = -1;
cout << "...Oh nevermind...ended" << endl;
}
}
counter++;
}
This is where I'm having trouble, I'm only getting #1 on the list to change. When only the user inputs numbers should be changed. How do I change the code to make this happen?
//now remove the desired card from the player's hand
for(int i = 0; i < sizeof(user_input); i++ )
{
if(user_input[i] = 1)
{
hand.setCard(0, myCard.getNextCard());//change #1 on the list
}else if(user_input[i] = 2)
{
hand.setCard(1, myCard.getNextCard());//#2
}
else if(user_input[i] = 3)
{
hand.setCard(2, myCard.getNextCard());//#3
}
else if(user_input[i] = 4)
{
hand.setCard(3, myCard.getNextCard());//#4
}
else if(user_input[i] = 5)
{
hand.setCard(4, myCard.getNextCard());//#5
}
}
cout << "You new hand is: " << endl
<<"1."<< hand.getCard(0).printName() << endl//then i ask what is the name of //the card in that position
<<"2."<< hand.getCard(1).printName() << endl
<<"3."<< hand.getCard(2).printName() << endl
<<"4."<< hand.getCard(3).printName() << endl
<<"5."<< hand.getCard(4).printName() << endl;
2 problems:
1) You don't initialize user_input. Do:
int user_input[6] = {};
to set all elements to 0.
2) Your conditions in the are all assigning instead of comparing...
if(user_input[i] = 1)
should be:
if(user_input[i] == 1)
// ^ - missing equal sign