C++: Printing A List - c++

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');
}

Related

I can't print a vector inside a switch case

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.

Functional Loop with user input C++

So I got an assignment to make a program that allows the user to select three favourite destinations in order. It repeats until the user decides to stop. Once the user decides to discontinue, the program then displays the total votes received for each destination according to preference by the users. One user will have three preferences and if the program repeats four times, it means four users’ preferences are recorded. Therefore a total of 12 preferences are recorded in this instance.
I have tried to limit input for the loop to work but it seems it will only work with a decision which is not necessary at the beginning of the program, which i want to remove altogether.
Also, I have tried to limit output for each of the decisions but it will only run once and then move on to the next choice. Is there any way to get a persistent entry prompt that will only continue after a valid input.
Lastly, is there any way I could improve the code by using switch/break statements instead of if/else?
Here's my code:
cout << "Do you want to go forth with this program?\nType y to confirm. The
program will exit if anything else is entered: ";
cin >> Decision;
while (Decision=="y")
{
cout << "\n\nNow please enter the code for which your destination corresponds to: " << endl; //first decision
cin >> Choice1;
if (Choice1 == 1)
{
LasVegas1++;
}
else if (Choice1 == 2)
{
Tokyo1++;
}
if (cin.fail())
{
cout << "Please enter a valid choice" << endl;
continue;
}
cout << " \nNow please enter the second code: " << endl; //second decision
cin >> Choice2;
if (Choice2 == 1)
{
LasVegas2++;
}
else if (Choice2 == 2)
{
Tokyo2++;
}
else
{
cout << "\nError! Please enter a valid code as shown above!\n";
cout << "\nNow please enter the second code: ";
cin >> Choice2;
}
cout << " \nNow please enter the third code: " << endl; //third decsion
cin >> Choice3;
if (Choice3 == 1)
{
LasVegas3++;
}
else
{
cout << "\nError! Please enter a valid code as shown above!\n";
cout << "\nNow please enter the third code: ";
cin >> Choice3;
}
cout << " \nDo you wish to select three more destinations? (Y/N): " << endl;
cin >> Decision;
}
What I would do is to put all your city variables into an array and then convert your three sets of code into a for loop. Something like:
for(int i = 0; i < 3; i++) {
if(Choice1 == 0) {
rome[i]++;
}
//etc
So that way you wouldn't need to repeat the same code three times. Also you only need one Choice variable. (You can just reset it at each iteration of the loop)
Additionally you could implement a switch statement to clean up the code a little:
switch(Choice1) {
case 1:
LasVegas1++;
break;
case 2:
Tokyo1++;
break;
case 3:
London1++;
break;
case 4:
Paris1++;
break;
case 5:
Dubai1++;
break;
case 6:
Mumbai1++;
break;
case 7:
NewYork1++;
break;
case 8:
Sydney1++;
break;
case 9:
Auckland1++;
break;
case 10:
Rome1++;
break;
case 11:
Other1++;
break;
}
It can be heavily simplified by the use of "Switch" and "Break".
Like the code that i have written. Have a look :
char input;
int choice;
void Permission() {
cout << "Do you want to go forth with this program ? (y to confirm)" << flush;
cin >> input;
cout << endl;
}
void Decision1() {
if(input == 'y') {
cout << "Now please enter the code for which your destination corresponds to : " << flush;
cin >> choice;
switch (choice) {
case 1:
cout << "LasVegas " << endl;
break;
case 2:
cout << "Tokyo " << endl;
break;
case 3:
cout << "London " << endl;
break;
case 4:
cout << "Paris " << endl;
break;
case 5:
cout << "Dubai " << endl;
break;
case 6:
cout << "Mumbai " << endl;
break;
case 7:
cout << "New York " << endl;
break;
case 8:
cout << "Sydney " << endl;
break;
case 9:
cout << "Auckland " << endl;
break;
case 10:
cout << "Rome " << endl;
break;
case 11:
cout << "Other " << endl;
break;
default:
cout << "Invalid option. Enter Again : " << flush;
cin >> choice;
}
cout << endl;
}
}
void Decision2() {
cout << "Now please enter the second code: " << flush;
cin >> choice;
switch (choice) {
case 1:
cout << "LasVegas " << endl;
break;
case 2:
cout << "Tokyo " << endl;
break;
case 3:
cout << "London " << endl;
break;
case 4:
cout << "Paris " << endl;
break;
case 5:
cout << "Dubai " << endl;
break;
case 6:
cout << "Mumbai " << endl;
break;
case 7:
cout << "New York " << endl;
break;
case 8:
cout << "Sydney " << endl;
break;
case 9:
cout << "Auckland " << endl;
break;
case 10:
cout << "Rome " << endl;
break;
case 11:
cout << "Other " << endl;
default:
cout << "Invalid option. Enter Again : " << flush;
cin >> choice;
}
cout << endl;
}
void Decision3() {
cout << "Now please enter the third code: " << flush;
cin >> choice;
switch (choice) {
case 1:
cout << "LasVegas " << endl;
break;
case 2:
cout << "Tokyo " << endl;
break;
case 3:
cout << "London " << endl;
break;
case 4:
cout << "Paris " << endl;
break;
case 5:
cout << "Dubai " << endl;
break;
case 6:
cout << "Mumbai " << endl;
break;
case 7:
cout << "New York " << endl;
case 8:
cout << "Sydney " << endl;
break;
case 9:
cout << "Auckland " << endl;
break;
case 10:
cout << "Rome " << endl;
break;
case 11:
cout << "Other " << endl;
break;
default:
cout << "Invalid option. Enter Again : " << flush;
cin >> choice;
}
cout << endl;
}
int main() {
Permission();
Decision1();
Decision2();
Decision3();
system("PAUSE");
return 0;
}
I don't know that how to get the loop at the default when the user enters the wrong option. I was able to give the "cin" once. Update this problem if you know how to.
Yes you could improve with a switch statement. Theres also something called a do while loop you should look into.

I'm not sure how to assign the values I want exactly

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

input validation for choosing an item with a char, getting errors with cin.fail

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.

C++ - Trouble aligning output

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.