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.
Related
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
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.
I have always used if else statements over switch statements, but I decided I wanted to try a switch out. I did the basic Coke Machine program with a switch and I cannot for the life of me figure out why it does not work how it should. When I use a number 1-5 for my input it continues to give the the switch default error message instead of the case cout statements (such as "You chose Coke"). Obviously something must be wrong that I am not seeing/
#include <iostream>
using namespace std;
int main()
{
int number;
cout << "Beverage List" << endl;
cout << "Coke = 1" << endl;
cout << "Dr. Pepper = 2" << endl;
cout << "Water = 3" << endl;
cout << "Sprite = 4" << endl;
cout << "Lemonade = 5" << endl << endl << endl;
cout << "Enter a number to choose a beverage: ";
cin >> number;
switch (number)
{
case '1':
cout << "You chose Coke";
break;
case '2':
cout << "You chose Dr. Pepper";
break;
case '3':
cout << "You chose Water";
break;
case '4':
cout << "You chose Sprite";
break;
case '5':
cout << "You chose Lemonade";
break;
default:
cout << "Error: Choice was not valid. Here is your money back.";
}
cout << "\n";
system("pause");
return 0;
}
The character '1' is not the same as the number 1.
Change
case '1':
to
case 1:
It looks like your case statements are comparing chars, not integers:
case '5':
Try this instead:
case 5:
Hi I am having some trouble getting the correct smallest value and the correct largest value . I know it has to do with the while loop. the rest of the program works great. I found the correct average , sum and number of integers
#include<iostream>
#include<fstream>
using namespace std;
int main()
{
ifstream inputfile;
char choice;
int NumberOfIntegers = 0,
SumOfIntegers = 0,
Average = 0 ,
LargestValue,
SmallestValue,
integer;
inputfile.open("random.txt");
if(!inputfile)
{
cout << "the file could not be open" << endl;
}
inputfile >> integer;
//initialize smallest and largest
SmallestValue = integer;
LargestValue = integer;
while(inputfile)
{
NumberOfIntegers++;
SumOfIntegers = SumOfIntegers + integer;
inputfile >> integer;
if( integer >> LargestValue || integer << SmallestValue)
{
if ( integer >> LargestValue)
LargestValue = integer;
else
SmallestValue = integer;
}
}
if(NumberOfIntegers > 0 )
{
Average = SumOfIntegers / NumberOfIntegers;
}
do
{
//Display Menu
cout << "Make a selection from the list" << endl;
cout << "A. Get the largest Value" << endl;
cout << "B. Get the smallest Value" << endl;
cout << "C. Get the sum of the values" << endl;
cout << "D. Get the average of the values" << endl;
cout << "E. Get the number of values entered" << endl;
cout << "F. End this program" << endl << endl;
cout << "Enter your choice --> ";
cin >> choice;
cout << endl;
switch (choice)
{
case 'a':
case 'A': cout << "The largest value is " << LargestValue << endl;
break;
case 'b':
case 'B': cout << "The smallest value is " << SmallestValue << endl;
break;
case 'c':
case 'C': cout << "The sum of the values entered is " << SumOfIntegers << endl;
break;
case 'd':
case 'D': cout << "The average of the values entered is " << Average << endl;
break;
case 'e':
case 'E': cout << "The number of values entered is " << NumberOfIntegers << endl;
break;
case 'f':
case 'F': cout << "Program is now ending" << endl;
return 1;
break;
default:
cout << choice << " is an invalid value. " << endl;
}
cout << endl;
} while( choice != 'f' || choice != 'F');
return 0;
}
integer >> LargestValue
Presumably that should be integer > LargestValue. >> is a shift operation, not a comparison. The same applies to <<.
You should also make sure you initialize LargestValue to something small and SmallestValue to something large. Otherwise you may miss outliers in your data.
Make your 'largest' & 'smallest' logic blocks separate -- there's no reason or correctness in joining them.
Note that for a list with only one item, that value will be both smallest and largest. Not only is it more complicated, it is incorrect to make these conditions mutually exclusive.
Use better names for your variables. Use "item" or "value" for what you are currently reading, everything is an integer so that is effectively meaningless. I prefer a lowercase first letter for variables.. been working in Java for a while :)
Avoid declaring variables before/ or outside of where they have meaningful value too, where possible.
int value;
inputfile >> value;
if (value > largestValue) {
largestValue = value;
}
if (value > smallestValue) {
smallestValue = value;
}
Also, you need to either detect 'first' or initialize smallest/largest to +/- MaxInt to ensure that the first value will be taken up.