I have a function that iterates through some parallel arrays and prints the contents at the loop control variable. I have another that is used throughout my program to print the names associated with the ID at value of loop control variable. Here are the 2 functions
void PrintName(int ID)
{
switch (ID)
{
case 0: cout << "computer(s)";
break;
case 1: cout << "pencil(s)";
break;
case 2: cout << "pen(s)";
break;
case 3: cout << "book(s)";
break;
case 4: cout << "beer(s)";
break;
case 5: cout << "ruler(s)";
break;
case 6: cout << "stereo(s)";
break;
case 7: cout << "refrigerator(s)";
break;
case 8: cout << "desk(s)";
break;
case 9: cout << "backpack(s)";
break;
}
}
void PrintSummary(InvIDList invIDs, ItemQuantity itemQuant, int totalWeight, int totalPurch, int budget)
{
cout << "ID NAME QUANTITY" <<endl;
cout << "--------------------------" <<endl;
for(int i = 0; i < 10; i++){
cout << invIDs[i];
PrintName(i);
cout << itemQuant[i] <<endl;
}
cout << "\n\nTotal Amount Spent: $" << totalPurch <<endl;
cout << "Amount of Budget Remaining: $" << budget <<endl;
cout << "Total Weight of Items Purchased: " << totalWeight <<endl;
}
I want the output to align nicely under ID, NAME, and QUANTITY, with ID being leftmost, QUANTITY being the rightmost, and NAME centered. Unfortunately I cannot figure out how to achieve this after hours of tinkering with the code, mainly getting QUANTITY aligned all the way to the right.
Instead of using the PrintName function, you want to return a string object to use with std::cout. In order to correctly align the columns you may want to look on the <iomanip> header and especially the std::setw(n) manipulator.
Here is an example, take note that while I set the column widths to 16 characters, what you should do is calculate the maximum number of characters for each category and change the widths accordingly. What is nice about this is that you can specify a different width for each column.
string ReturnName(int ID)
{
switch (ID)
{
case 0: return "computer(s)";
break;
case 1: return "pencil(s)";
break;
case 2: return "pen(s)";
break;
case 3: return "book(s)";
break;
case 4: return "beer(s)";
break;
case 5: return "ruler(s)";
break;
case 6: return "stereo(s)";
break;
case 7: return "refrigerator(s)";
break;
case 8: return "desk(s)";
break;
case 9: return "backpack(s)";
break;
}
}
void PrintSummary(InvIDList invIDs, ItemQuantity itemQuant, int totalWeight, int totalPurch, int budget)
{
cout << left << setw(16) << "ID";
cout << left << setw(16) << "NAME";
cout << left << setw(16) << "QUANTITY" << endl;
cout << "--------------------------------------" << endl;
for(int i = 0; i < 10; i++){
cout << left << setw(16) << invIDs[i];
cout << left << setw(16) << ReturnName(i);
cout << left << setw(16) << itemQuant[i] << endl;
}
cout << "\n\nTotal Amount Spent: $" << totalPurch <<endl;
cout << "Amount of Budget Remaining: $" << budget <<endl;
cout << "Total Weight of Items Purchased: " << totalWeight <<endl;
}
Don't print the name in PrintName, but rather just return the name as a string. Then in your loop you have all the information you need to properly align the columns.
Oh, and you might want to change the name of PrintName.
U have printed the heading as
cout << "ID NAME QUANTITY" <<endl;
U are assuming the spaces as given above but you never know how much space
invIDs[i]
and
PrintName(i);
take.So you can take care of the maximum length of each of these.For e.g. know what is the maximum length any of the output from switch can take etc.Then modify your heading print statement including that many spaces.
Related
This is my first question here. I am just beginning to learn C++ and I am stuck at this exercise:
Your program should display a menu options to the user as follows:
P--Print the vector
A--Add a number
M--Display mean of the number
S--Display the smallest number
L--Display the largest number
Q--Quit
Enter your choice:
Basically, I need to do a menu for these operations. I got stuck at the part of printing the vector. I already tried to use (for auto:....) and also tried with the normal index (int i = 0...), but the contents in the vector don't appear, only the message "This is your list of numbers:". I also tried to create a function to make sure that the user was inputting an integer in the A case, but did not know how to do it :(
This is my code:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
bool control_end = false;
do
{
cout << "Please enter your desired function within the menu: " << endl;
cout << endl;
cout << "P--Print list of numbers" << endl;
cout << "A--Add a number"<< endl;
cout << "M--Display mean of the number"<< endl;
cout << "S--Display the smallest number"<< endl;
cout << "L--Display the largest number"<< endl;
cout << "Q--Quit "<< endl;
cout << endl;
cout << "Enter your choice: ";
char letra{};
cin >> letra;
vector<int> vector{};
switch(letra)
{
case 'A':
case 'a':
{
cout << "Please enter the value (integer) to be added to vector: ";
int value_add;
cin >> value_add;
cout << endl;
vector.push_back(value_add);
//(later do it) create a function to ensure that the value is an integer
break;
}
case 'p':
case 'P':
{
cout << "This is your list of numbers: \n";
for (unsigned int i=0 ;i < vector.size(); i++)
cout << vector[i] << " ";
break;
}
case 'm':
case 'M':
cout << "test M";
break;
case 's':
case 'S':
cout << "test S";
break;
case 'L':
case 'l':
cout << "test L";
break;
case 'q':
case 'Q':
cout << "Thank you for using the program" << endl;
control_end = true;
break;
default:
cout << "Invalid char. " << endl;
cout << endl;
break;
}
for(auto vec: vector)
cout << vec << endl;
}
while (control_end !=true);
return 0;
}
You created the variable vector inside your loop, so at the end of the loop the variable get destroyed and a new empty one is created on the next iteration. So, if you want your variable to retain values between loop iterations, you should declare it outside of the loop scope, the same way you did with the variable control_end.
The code below contains a table I created numbering from 1 to 10 in reverse order. (This is the code without breaks, later changed.)
#include <iostream>
using namespace std;
int main()
{
switch(1) {
case 1: cout << "1. blue" << endl;
case 2: cout << "2. orange.." << endl;
case 3: cout << "3. yellow.." << endl;
case 4: cout << "4. green.." << endl;
case 5: cout << "5. purple.." << endl;
case 6: cout << "6. red.." << endl;
case 7: cout << "7. teal.." << endl;
case 8: cout << "8. aqua.." << endl;
case 9: cout << "9. white.." << endl;
case 10: cout << "10. gray.." << endl;
}
}
I am trying to make it so that each time the loop runs, the program will output the message corresponding to the next lower number, one by one. (Code with breaks)
#include <iostream>
using namespace std;
int main() {
for(int i = 10; i>0; --i){
switch(i) {
case 1: cout << "1. blue" << endl;
break;
case 2: cout << "2. orange.." << endl;
break;
case 3: cout << "3. yellow.." << endl;
break;
case 4: cout << "4. green.." << endl;
break;
case 5: cout << "5. purple.." << endl;
break;
case 6: cout << "6. red.." << endl;
break;
case 7: cout << "7. teal.." << endl;
break;
case 8: cout << "8. aqua.." << endl;
break;
case 9: cout << "9. white.." << endl;
break;
case 10: cout << "10. gray.." << endl;
break;
}
}
}
I am having trouble looping down the list, and listing each number/color one by one.
At the end of listing each item, I would like the program to ask the user if they would like to Stop, or Restart the loop.
You need to create a variable to hold the variable that will be passed into your switch statement. Your switch statement needs to start from 10 and go down because you want to print case 10 first.
#include <iostream>
using namespace std;
int main() {
for(int i = 10; i>0; --i){
switch(i) {
case 1: cout << "1. blue" << endl;
break;
case 2: cout << "2. orange.." << endl;
break;
case 3: cout << "3. yellow.." << endl;
break;
case 4: cout << "4. green.." << endl;
break;
case 5: cout << "5. purple.." << endl;
break;
case 6: cout << "6. red.." << endl;
break;
case 7: cout << "7. teal.." << endl;
break;
case 8: cout << "8. aqua.." << endl;
break;
case 9: cout << "9. white.." << endl;
break;
case 10: cout << "10. gray.." << endl;
break;
}
}
}
It was a bit confusing how you were explaining before, I think i got it now.
As said on the comments switch works but probably isn't the best way, I will show you how I would do it, if you really want it done with switch just say in the comments and I will update my answer.
I think what you really want is to print one option and after ask if the user wants to stop or start from the beginning, if not just continue (Just comment if it isn't this).
#include <iostream>
#include <array>
using namespace std;
int main()
{
array<string, 10> colors {"1. blue", "2. orange..", "3. yellow..", "4. green..", "5. purple..", "6. red..", "7. teal..", "8. aqua..", "9. white..", "10. gray.."};
for(int i = colors.size() - 1; i >= 0; --i)
{
cout << colors[i] << endl;
cout << endl << "Would you like to stop[s/S] or restart[r/R]?: ";
char input;
if (cin >> input)
{
if (tolower(input) == 's')
break;
else if (tolower(input) == 'r')
i = colors.size(); // To restart should be one more than the last index, it's going to be decreased at the end of loop
}
cout << endl;
}
}
So basically the code has two parts, first the printing which I changed the switch statement to and array.
array<string, 10> colors {"1. blue", "2. orange..", "3. yellow..", "4. green..", "5. purple..", "6. red..", "7. teal..", "8. aqua..", "9. white..", "10. gray.."};
for(int i = colors.size() - 1; i >= 0; --i)
{
cout << colors[i] << endl;
}
So this way you could even add more to the array and the code would still work, just starts at the end of the array and prints one by one.
The second part is were it asks the user if he wants to stop or restart.
char input;
if (cin >> input)
{
if (tolower(input) == 's')
break;
else if (tolower(input) == 'r')
i = colors.size(); // To restart should be one more than the last index, it's going to be decreased at the end of loop
}
If the user types s just breaks out of the loop, if he types r resets the i variable to the last index of the array (although the array is indexed at 0, you can't put size() - 1 because at the end of the loop the variable i is decreased).
As requested here is the switch version
#include <iostream>
using namespace std;
int main()
{
while (true)
{
for(int i = 10; i>0; --i)
{
switch(i)
{
case 1: cout << "1. blue" << endl;
break;
case 2: cout << "2. orange.." << endl;
break;
case 3: cout << "3. yellow.." << endl;
break;
case 4: cout << "4. green.." << endl;
break;
case 5: cout << "5. purple.." << endl;
break;
case 6: cout << "6. red.." << endl;
break;
case 7: cout << "7. teal.." << endl;
break;
case 8: cout << "8. aqua.." << endl;
break;
case 9: cout << "9. white.." << endl;
break;
case 10: cout << "10. gray.." << endl;
break;
}
}
cout << endl << "Would you like to stop[s/S] or restart[r/R]?: ";
char input;
if (cin >> input && tolower(input) != 'r')
break;
cout << endl;
}
}
I want to suggest a different approach to solve your problem.
Think of what you are trying to do and use one or more function calls to do that from main instead of having the code inside main. You core functionality is to print a color given an integer value.
From main, that would look like:
void printColor(int i);
int main()
{
for (int i = 10; i>0; --i)
{
printColor(i);
}
}
In the implementation of printColor, you would use:
std::string getColor(int i);
void printColor(int i)
{
std::cout << i << ". " << getColor(i) << std::endl;
}
You can implement getColor as:
std::string getColor(int i)
{
switch (i)
{
case 1:
return "blue";
case 2:
return "orange";
...
}
// If value is different than the known values in the switch statement,
// we have an unknown color
return "Unknown";
}
For repeating the core function in main, you can use a while loop.
Here's everything put together.
#include <iostream>
#include <string>
void printColor(int i);
std::string getColor(int i);
bool getRepeat();
int main()
{
bool repeat = true;
while ( repeat )
{
for (int i = 10; i>0; --i)
{
printColor(i);
}
repeat = getRepeat();
}
}
void printColor(int i)
{
std::cout << i << ". " << getColor(i) << std::endl;
}
std::string getColor(int i)
{
switch (i)
{
case 1:
return "blue";
case 2:
return "orange";
case 3:
return "yellow";
case 4:
return "green";
case 5:
return "purple";
case 6:
return "red";
case 7:
return "teal";
case 8:
return "aqua";
case 9:
return "white";
case 10:
return "gray";
}
// If value is different than the known values in the switch statement,
// we have an unknown color
return "Unknown";
}
bool getRepeat()
{
std::cout << "Stop or Continue (S/C)? ";
char c;
std::cin >> c;
return (c == 'c' || c == 'C');
}
I need cherries, oranges, plumes, bells, melons, or bars to be randomly picked in the case statements and in a way I can then display what was chosen so I can compare them, but I'm not sure how.
For example, I was hoping when I printed slot1, slot2, and slot3, I would get the names of which case statement inside each of the three switches were chosen.
Not their numbers. (The program isn't done yet so it's quite messy right now)
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <string>
using namespace std;
int main()
{
int slot1;
int slot2;
int slot3;
double won;
double money;
string cherries;
string oranges;
string plums;
string bells;
string melons;
string bars;
string doAgain;
do
{
cout << "We are going to be playing a slot machine game today." << endl;
cout << "Please enter the amount of money you'd like to insert into the slot machine." << endl;
cin >> money;
cout << "You put in $" << money << endl;
srand(time(0));
slot1=rand()%6+1;
slot2=rand()%6+1;
slot3=rand()%6+1;
switch (slot1)
{
case 1:
cout << cherries << endl;
case 2:
cout << oranges << endl;
break;
case 3:
cout << plums << endl;
break;
case 4:
cout << bells << endl;
break;
case 5:
cout << melons << endl;
break;
case 6:
cout << bars << endl;
}
switch (slot2)
{
case 1:
cout << melons << endl;
break;
case 2:
cout << bells << endl;
break;
case 3:
cout << bars << endl;
break;
case 4:
cout << plums << endl;
break;
case 5:
cout << oranges << endl;
break;
case 6:
cout << cherries << endl;
}
switch (slot3)
{
case 1:
cout << bars << endl;
break;
case 2:
cout << plums << endl;
break;
case 3:
cout << melons << endl;
break;
case 4:
cout << bells << endl;
break;
case 5:
cout << oranges << endl;
break;
case 6:
cout << cherries << endl;
}
cout << "The numbers you got were " << slot1 << ", " << slot2 << ", " << slot3 << endl;
cout << "Would you like to play again?" << endl;
cin >> doAgain;
if(doAgain!= "yes")
{
cout << "The total amount of money you put in the slot machine is" << money << endl;
cout << "The total amount of money you won is $" << won << endl;
}
}
while(doAgain=="yes");
return 0;
}
enter code here
You have declared strings for all the various fruits, but you don't assign any actual string values to them. ie string cherries = "cherries"
Just printing slot1 will only print an int as you have discovered. C++ doesn't know that you also want to print the name as well. You need to include your string as part of the cout statement
So here's my code
do
{
cout << "Welcome to our Coffee Shop! Here are the options: " << endl;
cout << "C - Coffee ($1.50)" << endl;
cout << "T - Tea ($1.00)" << endl;
cout << "S - Soda ($1.00)" << endl;
cout << "J - Juice ($1.50)" << endl;
cout << "M - Manager Special ($2.00)" << endl;
cout << "X - Finish Order" << endl;
cout << "What drink would you like? Enter C, T, S, J, M, or X." << endl;
cin >> input;
//does certain actions for a certain character
if(input)
{
switch(input)
{
case 'C':
case 'c': total += coffeePrice;
coffeeCount++;
cout << "Thanks! You have ordered coffee." << endl;
break;
case 'T':
case 't': total += teaPrice;
teaCount++;
cout << "Thanks! You have ordered tea." << endl;
break;
case 'S':
case 's': total += sodaPrice;
sodaCount++;
cout << "Thanks! You have ordered soda." << endl;
break;
case 'J':
case 'j': total += juicePrice;
juiceCount++;
cout << "Thanks! You have ordered juice." << endl;
break;
case 'M':
case 'm': total += specialPrice;
specialCount++;
cout << "Thanks! You have ordered the manager special." << endl;
break;
default:
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
break;
}
}
else
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
I've been trying to make a menu that only reads one character and does something as a result. The problem is when I enter a string that has multiple c's like "cccc" the menu repeats itself 4 times. Or if I enter a string that has some c's and other's that are not correct responses like, "ccddcc" the menu will say thanks for the coffee twice then repeat the menu twice and then say thanks for the coffee twice again. Is there a way to stop this from happening. I just want it to ignore any response other than a 'c' or a correct menu option.
What I would think the problem here is, is that input'is a char. Thus, when you input cccc, it will read in the first char and move on, come back and see that there are still more c's in the std input waiting to be processed, so it will take that next c and process again. I would recommend making your input var a string, and then if that string was greater than size 1, either leave or just use the first char.
char input[256]; // Could probably be a string, but I am used to C for this
do
{
cout << "Welcome to our Coffee Shop! Here are the options: " << endl;
cout << "C - Coffee ($1.50)" << endl;
cout << "T - Tea ($1.00)" << endl;
cout << "S - Soda ($1.00)" << endl;
cout << "J - Juice ($1.50)" << endl;
cout << "M - Manager Special ($2.00)" << endl;
cout << "X - Finish Order" << endl;
cout << "What drink would you like? Enter C, T, S, J, M, or X." << endl;
cin >> input;
switch(input[0])
{
case 'C':
case 'c': total += coffeePrice;
coffeeCount++;
cout << "Thanks! You have ordered coffee." << endl;
break;
case 'T':
case 't': total += teaPrice;
teaCount++;
cout << "Thanks! You have ordered tea." << endl;
break;
case 'S':
case 's': total += sodaPrice;
sodaCount++;
cout << "Thanks! You have ordered soda." << endl;
break;
case 'J':
case 'j': total += juicePrice;
juiceCount++;
cout << "Thanks! You have ordered juice." << endl;
break;
case 'M':
case 'm': total += specialPrice;
specialCount++;
cout << "Thanks! You have ordered the manager special." << endl;
break;
default:
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
break;
}
}
else
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
cin is really difficult for me to understand with c++.
I want to choose an item on the menu but I want it to be clean, however I am running into issues with cin.fail.
I realize cin.fail checks the datatype so I should be clear when it comes to other data types.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int number;// define an integer variable called number
float cost;// a floating point variable called cost,
char beverage;// and a character variable called beverage
bool validBeverage;
cout << fixed << showpoint << setprecision(2);
do
{
cout << endl << endl;
cout << "Hot Beverage Menu" << endl << endl;
cout << "A: Coffee $1.00" << endl;
cout << "B: Tea $ .75" << endl;
cout << "C: Hot Chocolate $1.25" << endl;
cout << "D: Cappuccino $2.50" << endl <<endl << endl;
cout << "Enter the beverage A,B,C, or D you desire" << endl;
cout << "Enter E to exit the program" << endl << endl;
do
{
cin >> beverage;// Fill in the code to read in beverage
if (cin.fail)
{
cout << "You have entered an invalid value." << endl
<< "Please enter the letter corresponding to the menu." << endl;
}
} while (cin.fail);
switch(beverage)
{
case 'a': validBeverage = true;
case 'A': validBeverage = true;
case 'b': validBeverage = true;
case 'B': validBeverage = true;
case 'c': validBeverage = true;
case 'C': validBeverage = true;
case 'd': validBeverage = true;
case 'D': validBeverage = true;
break;
default: validBeverage = false;
}// end switch beverage
if (validBeverage == true)
{
do
{
cout << "How many cups would you like?" << endl;
// Fill in the code to read in number
cin >> number;
if (cin.fail() || number <= 0)
{
cout << "You have entered an invalid value." << endl <<
"Please enter an integer greater than 0." << endl;`enter code here`
}
} while (cin.fail() || number <= 0);
}
switch (beverage)// Fill in the code to begin a switch
statement that is controlled by beverage
{
case 'a': (float)cost = number * 1.0;
cout << "The total cost is $ " << cost << endl;
break;
case 'A': (float)cost = number * 1.0;
cout << "The total cost is $ " << cost << endl;
break;
case 'b': (float)cost = number * 0.75;// Fill in the
code to give the case for tea ( $0.75 a cup)
cout << "The total cost is $ " << cost << endl;
break;
case 'B': (float) cost = number * 0.75;// Fill in the
code to give the case for hot chocolate ($1.25 a cup)
cout << "The total cost is $ " << cost << endl;
break;
case 'c': (float)cost = number * 1.25;
cout << "The total cost is $ " << cost << endl;
break;
case 'C': (float)cost = number * 1.25;
cout << "The total cost is $ " << cost << endl;
break;
case 'd': (float)cost = number * 2.50;// Fill in the
code to give the case for cappuccino ($2.50 a cup)
cout << "The total cost is $ " << cost << endl;
break;
case 'D': (float)cost = number * 2.50;// Fill in the
code to give the case for cappuccino ($2.50 a cup)
cout << "The total cost is $ " << cost << endl;
break;
case 'e':
cout << "Please come again." << endl;
break;
case 'E':
cout << " Please come again." << endl;
break;
default:cout << "Invalid Selection."; // Fill in the
code to write a message indicating an invalid selection.
cout << " Try again please" << endl;
}
}while (beverage != 'e' || beverage != 'E'); // Fill in the code to
finish the do-while statement with the condition that beverage does not
equal E or e.
// Fill in the appropriate return statement
return 0;
}
Try using: if(!cin) which checks for data type on input.