how do i pick a memory in an array that i create after displaying the array value. how to slect thte value with cin when the program run - arrays

string bookname [5] = {"STPM BOOKS","SPM BOOKS","PMR BOOKS","TEXT BOOK","PRACTICAL BOOK"};
float price [5] = {30.90,24.90,19.90,45.90,15.90};
for(int i = 0; i < 5 ; i++)
{
cout << i+1 << "book name " << bookname[i] << " ---- RM " << price[i] << endl;}
i want to select the value for example like stpm books and its price from the array and display it to cout after selecting from a cin and doing the selection when the code was excercuted
}

Based on your updated query, asking for an exit condition, I have modified the code. Please note that I have used getline(cin, answer) to handle the input. I use getline() because I am less likely to mess up when I use getline() over cin >> answer.
Note that getline(cin, answer) does a few things for you:
Returns true if input was received
Fills in the answer
Gets an entire line, until user provides new line
Thus, the line while (std::getline(std::cin, answer) && answer != "n") will get an entire book, even if there are spaces. The && allows for a check of the answer for "n" before entering the while loop's body.
As answer is a std::string, the comparison is to "n", not 'n'.
#include <iostream>
#include <string>
#include <iomanip> // setprecision
int main()
{
std::string bookname[5] =
{"STPM BOOKS", "SPM BOOKS", "PMR BOOKS", "TEXT BOOK", "PRACTICAL BOOK"};
float price[5] = {30.90, 24.90, 19.90, 45.90, 15.90};
std::string answer;
float cost;
std::cout << "Please provide the name of a book or type 'n' to exit"
<< std::endl;
// get one line into answer, and also exit while if answer is "n"
while (std::getline(std::cin, answer) && answer != "n") {
bool found = false;
for (int i = 0; i < 5; i++) {
if (bookname[i] == answer) {
std::cout << "The book " << bookname[i] << " costs $" << std::fixed
<< std::setprecision(2) << price[i] << std::endl;
found = true;
break; // /no need to continue inside the for loop
}
}
// on last loop, give up
if (!found) {
std::cout << "The book " << answer << " is not in our inventory"
<< std::endl;
}
}
}

Related

if loop inside a void function not working

So I'm doing a program for a class, and I set up an if loop inside a function definition to set parameters for entries. I'm supposed to be taking inputs between 0 and 10 only. But it's only catching the numbers that are less than 0. It won't catch the numbers larger than 10.
int main()
{
float score1, score2, score3, score4, score5;
cout << endl;
cout << "Judge #1: " << endl;
getJudgeData(score1);
cout << "Judge #2: " << endl;
getJudgeData(score2);
cout << "Judge #3: " << endl;
getJudgeData(score3);
cout << "Score #4: " << endl;
getJudgeData(score4);
cout << "Score #5: " << endl;
getJudgeData(score5);
calcScore(score1, score2, score3, score4, score5);
return 0;
}
void getJudgeData (float &score)
{
cin >> score;
if(score < 0 || score > 10)
{
cout << "Error: Please enter a score between 0 and 10." << endl;
cin >> score;
}
}
Please change the if condition in your getJudgeData function into a while loop:
void getJudgeData (float &score)
{
cin >> score;
while (score < 0 || score > 10)
{
cout << "Error: Please enter a score between 0 and 10." << endl;
cin >> score;
}
}
Otherwise the condition will be only checked once, means for the first input of every judge. This isn't intended, if I understood your issue correctly.
Please find more information regarding the while loop here:
while

check order of array in c, using recursion and malloc [duplicate]

I am trying to debug a recursive function used to validate user input and return a value when the input is OK. The function looks like this:
double load_price()
{
double price;
Goods * tempGd = new Goods();
cin >> price;
while (!cin)
{
cin.clear();
#undef max
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout << endl;
cout << "You didn't enter a number. Do so, please: ";
cin >> price;
} // endwhile
if (!tempGd->set_price(price))
{
cout << endl;
cout << "The price " << red << "must not" << white << " be negative." << endl;
cout << "Please, insert a new price: ";
load_price();
}
else
{
delete tempGd;
return price;
}
}
The method set_price() of Goods class looks as follows
bool Goods::set_price(double price)
{
if (price> 0)
{
priceSingle_ = price;
priceTotal_ = price* amount_;
return true;
}
return false;
}
I tried drawing the problem on a paper but all my diagrams seem to look the way my function already looks like. I think there are some problems with returns, but I do not know where.
Help would be greatly appreciated.
You're not using the return value of the recursive call. You need to do:
return load_price();
Who talked you into using recursion for that problem?
#undef max
double load_price()
{
for(;;) {
double price;
cin >> price;
if (!cin)
{
cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
cout << endl;
cout << "You didn't enter a number. Do so, please: ";
continue;
}
if (!Goods().set_price(price))
{
cout << endl;
cout << "The price " << red << "must not" << white << " be negative." << endl;
cout << "Please, insert a new price: ";
continue;
}
return price;
}
}

On the output in the for loop it is displaying zero and not accepting the input I cannot figure out what i am doing wrong here

#include <iostream>
#include <exception>
using namespace std;
class Inventory{
friend istream& operator>>(istream&, Inventory);
friend ostream& operator<<(ostream&, Inventory);
private:
int stock;
int quant;
int price;
public:
Inventory(int=0,int=0,double=0);
};
Inventory::Inventory(int s, int q, double p){
stock=s;
quant=q;
price=p;
}
istream& operator>>(istream& in, Inventory){
int s;
int q;
double p;
cout << "Enter stock number: ";
in >> s;
cout << "Enter quantity: ";
in >> q;
cout << "Enter price: ";
in >>p;
Inventory inv(s,q,p);
return in;
}
ostream& operator<<(ostream& out, Inventory inv){
out << "The stock number is: " << inv.stock << endl << "The quantity is: " <<
inv.quant << endl << "The price is: " << inv.price << endl;
return out;
}
int main()
{
Inventory inv[5]={};
for(int i = 0; i <5; i++){
cin >> inv[i];
}
cout<<"------------------------" << endl;
for(int i=0;i<5;i++){
cout<<inv[i];
cout<<"------------------------" << endl;
}
return 0;
}
I can not figure out why when I use the overloaded << operator in the for loop it is displaying zero's, am I not storing the price, quantity and price to the object array correctly? I have tried not using a contructor and using one it did not make a difference, any ideas why the integers and double are not storing to the array?
Your were close! See my // change here comment markers (there are several) in the code below.
The 0's had nothing to do with the << overload, but rather the >> overload.
The deal is that you can use the 'in' istream to input directly to the class variables (without trying to call some other function, or a need for extra variables) in the >> overload, but you need to pass an Inventory reference to do so.
I was surprised that there was no error trying to set primitives to 0 in the constructor parameters?? (I'm likely very 'rusty' on newer C++ handling, been over 15+ years for me), but anyway:
#include <iostream>
#include <exception>
using namespace std;
class Inventory{
friend istream& operator>>(istream&, Inventory&); // change here (Inventory reference)
friend ostream& operator<<(ostream&, Inventory);
private:
int stock;
int quant;
double price; // change here
public:
Inventory(int,int,double); // change here
};
Inventory::Inventory(int s = 0, int q = 0, double p = 0){ // change here
stock=s;
quant=q;
price=p;
}
istream& operator>>(istream& in, Inventory& inv){ // change here (inventory reference)
// change here (removed variables)
cout << "Enter stock number: ";
in >> inv.stock; // change here
cout << "Enter quantity: ";
in >> inv.quant; // change here
cout << "Enter price: ";
in >> inv.price; // change here
// change here (removed function call)
return in;
}
ostream& operator<<(ostream& out, Inventory inv){
out << "The stock number is: " << inv.stock << endl << "The quantity is: " <<
inv.quant << endl << "The price is: " << inv.price << endl;
return out;
}
int main()
{
const int ITEMS = 5; // change here (constant to replace hard-coded value)
Inventory inv[ITEMS]={}; // change here (use the constant)
for(int i = 0; i <ITEMS; i++){ // change here (use the constant)
cin >> inv[i];
}
cout<<"------------------------" << endl;
for(int i=0;i<ITEMS;i++){ // change here (use the constant)
cout<<inv[i];
cout<<"------------------------" << endl;
}
return 0;
}
Give that a run and see how it goes:
Here's my example output when I changed the constant (my change inside the main function) to 2 for a basic test run:
Enter stock number: 123
Enter quantity: 4
Enter price: 2.1
Enter stock number: 467
Enter quantity: 1
Enter price: 1.2
------------------------
The stock number is: 123
The quantity is: 4
The price is: 2.1
------------------------
The stock number is: 467
The quantity is: 1
The price is: 1.2
------------------------

C++ How to Increment Int Variable From String Array Element

I'm wondering if there is a way to increment an int variable when a specific string array element is called? I'm working on a project for fun and have run into a roadblock. The goal of my project is to have a program that determines what genres of electronic music the user likes. The program will present two DJ's and ask the user which one they prefer or allow them to select neither. Each DJ will have up to three genres that they mainly specialize in, and I have created int variables for each (with all being set to 0). Once a user selects a DJ, I want points to be assigned to each genre variable in which the DJ is associated with. I'm unsure of how to set up this rule as everything I have attempted so far has failed (two example attempts are commented out in the code). Eventually my plan is to develop logic to have the DJ's randomly selected, however I need to have the genre tally allocation set up first. Is there any way this can be done? Any help would be greatly appreciated. Cheers!
###include "stdafx.h"
###include < iostream>
###include < iomanip>
###include < string>
###include < array>
###using namespace std;
int main()
{
cout << "Hello! This program is designed to figure out what Electronic Music you like based on artists presented and the answers you choose...\n" << endl;
cout << "When you are ready to begin press \"Enter\"..." << endl;
getchar();
int bigRoom = 0;
int deepHouse = 0;
int drumBass = 0;
int dubstep = 0;
int electroHouse = 0;
int futureHouse = 0;
int hardDance = 0;
int house = 0;
int progressiveHouse = 0;
int techno = 0;
int trance = 0;
int trap = 0;
string textArray[5]{ "DeadMau5", "Armin Van Buuren", "Avicii", "Ferry Corsten", "Kaskade"};
string answer;
cout << "Select the DJ you prefer by number. Otherwise select 3 if you don't know them. " << endl; //Haven't coded option 3 yet.
cout << "1 - " << textArray[1] << endl;
cout << "2 - " << textArray[2] << endl;
cin >> answer;
/*
if (textArray[1]) {
++trance;
}
for (textArray[1]) {
++trance;
}
*/
if (answer == "1") {
cout << "You have selected: " << textArray[1] << endl;
}
else if (answer == "2") {
cout << "You have selected: " << textArray[2] << endl;
}
//cout << trance << endl;
}
You can increment each tally once the user has selected a DJ:
if (answer == "1") {
cout << "You have selected: " << textArray[1] << endl;
++trance;
// ++ ohter genres you want to increment
}
else if (answer == "2") {
cout << "You have selected: " << textArray[2] << endl;
++trance;
// ++ ohter genres you want to increment
}

Issue with FOR loops and IF statement

Trying to display # of each combo ordered and total price. Not sure why it won't store values in A, B, and C. Novice programmer here, so be easy. Been having the problem with if statements for a while, so obviously I'm doing the whole if statement thing incorrectly.
#include <iostream>
using namespace std;
int main( )
{
int group = 0;
char combo = ' ';
int A = 0;
int B = 0;
int C = 0;
double total = 0.0;
cout << "How many customers are in the group? ";
cin >> group;
for (int counter = 0; counter < group; counter = counter + 1)
{
cout << "Enter combo ordered: ";
cin >> combo;
if (combo = A)
{
A = A + 1;
cout << "Enter combo ordered: ";
cin >> combo;
}
else if (combo = B)
{
B = B + 1;
cout << "Enter combo ordered: ";
cin >> combo;
}
else if (combo = C)
{
C = C + 1;
cout << "Enter combo ordered: ";
cin >> combo;
}
total = A*6 + B*6.25 + C*5.75;
}
cout << "# of Combo A ordered: " << A << endl;
cout << "# of Combo B ordered: " << B << endl;
cout << "# of Combo C ordered: " << C << endl;
cout << "Total price: $" << total << endl;
system("pause");
return 0;
}
For-loop should be for (int counter = 0; counter < group; counter++)
If statement should use == for equality. = is for assignment only.
Your if statement needs to quote the character you are comparing: if (combo == 'A') {. It is also possible that you'll need to access combo as an array of characters, like so: if (combo[0] == 'A') {
I think you may need to tweak just a few things; a few compilers don't like it when you compute a double using int and there is no reason to not use double here since the program is small. Also a few syntax errors (i.e. with = instead of ==). Have you tried displaying your output in an isolated way? Something like:
main(){
double A = 1;
double B = 2;
double C = 3;
double total = A*6 + B*6.25 + C*5.75;
cout << "# of Combo A ordered: " << A << endl;
cout << "# of Combo B ordered: " << B << endl;
cout << "# of Combo C ordered: " << C << endl;
cout << "Total price: $" << total << endl;
system("pause");
return 0;
}
Your corrected code:
#include <iostream>
using namespace std;
int main( )
{
int group = 0;
char combo = ' ';
double A = 0;
double B = 0;
double C = 0;
double total = 0.0;
cout << "How many customers are in the group? ";
cin >> group;
for (int counter = 0; counter < group; counter++)
{
cout << "Enter combo ordered: ";
cin >> combo;
if (combo == 'A')
{
A++;
}
else if (combo == 'B')
{
B++;
}
else if (combo == 'C')
{
C++;
}
cout << "Enter combo ordered: ";
cin >> combo;
}
total = A*6 + B*6.25 + C*5.75;
cout << "# of Combo A ordered: " << A << endl;
cout << "# of Combo B ordered: " << B << endl;
cout << "# of Combo C ordered: " << C << endl;
cout << "Total price: $" << total << endl;
system("pause");
return 0;
}
I would also display your value for group to make sure that the if loop is even running at least once. There are a few fault points here that I would test individually.
EDIT:
Maybe test this:
#include <iostream>
using namespace std;
int main( )
{
int group = 0;
cout << "How many customers are in the group? ";
cin >> group;
for (int counter = 0; counter < group; counter++)
{
cout << "Test success";
}
to see if you are even entering into your for loop.

Resources