I have this little program I am creating. In lamens terms, I am wanting to make a menu where a user can input his selection, it takes him to the predetermined area and after he is done it takes him back to the menu where he can make a different selection. I have gotten down where it displays when you press 1 (you will see what i mean with the code). But after it goes through what it is supposed to do, it doesn't go back to the menu it just continues on to the second option. Also say you are at the menu and you want to start with the 2nd option it just starts with the first. Can anyone please help me with this...
#include <iostream>
using namespace std;
int main()
{
int option;
cout << "Hello there...\n\nToday we are going to do a little fun project that I created.\n\n";
cin.get();
cout << "\nAs we progress throughout this program, I will explain the different things\n";
cout << "that we are going to do. We will be covering some basic C++ excersises.";
cout << "\n\nFirst and foremost we will begin by covering what I have learned so far....\n\n";
cin.get();
cout << "The first topic we will cover will include what is known as 'variables'.\n";
cout << "what are variables you ask?";
cin.get();
int var = 1;
int main=1;
do
{
cout << "\n\n\nEnter the number of one of the following and I will explain!\n";
cout << "1.integer 2.boolian 3.floats 4.doubles 5.character";
cout << "\n\n[when you are done type 'done' to continue]\n\n";
cin >> option; //this is where the user puts in his option (1,2,3,4,5,6) I have only 1 and 2 complete
if (option = 1) //starts with this regardless of input
{
cin.ignore();
cout << "\n\n\nInteger is the variable abbreviated as 'int' this allows C++ to only";
cout << "\nread whole and real numbers. C++ takes this number as stores it\n";
cout << "in a user-defined variable (you can make up what that variable is..)\n";
cin.get();
cout << "an example syntax would be:";
cout << "\n\nint var=[whole;real number]";
cin.get();
cout << "\n\nwhat this implies is that you have 'declared' to the system";
cout << "\nthat you are going to use an 'int' that you have named 'var'\n";
cout << "and in this 'var' you are going to store a real and whole number\ninside of it.";
cout << "\n\nPress any key to go back to menu";
cin.get();
}
else if (option = 2); //continues with this without going back to menu.
{
cin.ignore();
cout << "\n\n\nBoolian is the variable abbreviated as 'bool' this allows C++ to only";
cout << "\nread true or false ( 0 or 1 ). C++ takes this number as stores it\n";
cout << "in a user-defined variable (you can make up what that variable is..)\n";
cin.get();
cout << "an example syntax would be:";
cout << "\n\nbool var=[true or false]";
cin.get();
cout << "\n\nwhat this implies is that you have 'declared' to the system";
cout << "\nthat you are going to use an 'bool' variable that you have named 'var'\n";
cout << "and in this 'var' you are going to store a either a true or false\ninside of it.";
cout << "\n\nPress any key to go back to menu";
cin.get();
}
} while (var = 1);
}
The problem lies with the comparison operator
1) if (option = 1) , use if(option == 1)
2) else if (option = 2); , use else if(option == 2) , remove the semicolon
3) while(var = 1) ; , use while(var ==1 );
comparision in C++ is done with the == operator:
e.g.
if (option == 1)
if (option == 2)
while (var == 1);
Related
I'm working on creating a menu with error checking and this is what I've come up with, but I can't seem to get it to work.
#include <iostream>
using namespace std;
int main()
{
char option; // user's entered option will be saved in this variable
int error1 = 0;
//Displaying Options for the menu
cout << "There are three packages available." << endl;
cout << "Monthly Price - Price per MB for overages (excluding C)" << endl;
cout << "A) $15 - $.06 for each MB after 200 MB." << endl;
cout << "B) $25 - $.02 for each MB after 2,000 MB ( approx. 2 GB)." << endl;
cout << "C) $50 - Unlimited data." << endl;
do //do-while loop starts here
{
//Prompting user to enter an option according to menu
cout << "Please enter which plan you currently have : ";
cin >> option; // taking option value as input and saving in variable "option"
if(option == 'A' || option == 'a') // Checking if user selected option 1
{
cout << "You chose a" << endl;
error1 = 1;
}
else if(option == 'B' || option == 'b') // Checking if user selected option 2
{
cout << "You chose b" << endl;
error1 = 1;
}
else if(option == 'C' || option == 'c') // Checking if user selected option 3
{
cout << "You chose c" << endl;
error1 = 1;
}
else //if user has entered invalid choice
{
//Displaying error message
error1 = 0;
cout << "Invalid Option entered";
}
}
while(error1 = 0); //condition of do-while loop
return 0;
}
When typing in an incorrect value, the output will be Invalid Option entered; however, it won't loop back to the beginning and prompt the user for input again.
Why is it doing this?
Change
while(error1 = 0); //condition of do-while loop
into this
while(error1 == 0); //condition of do-while loop
in the first option you just assign 0 to error1 and then error1 is being tested as boolean which means 0 is FALSE and non-0 is TRUE. So sonce the condition in the while is evaluated as FALSE, the loop ends.
You are assigning 0 to error1 inside the while, which is always false, so the loop will not repeat. Change while(error1=0); to while(error1==0);
Just as complement: consider invert the expression thus:
while (0 = error1);
In this way the compiler will stop you if you forget the additional = or confound the assignment with the equal operator
Using C++ (g++-4.7 on Mint 16).
Code is a unrefined (and unfinished) Tic-Tac-Toe game.
#include <iostream>
using namespace std;
int main()
{
//initial data
char turn='A';
char ttt[] = {'1','2','3','4','5','6','7','8','9'};
int move;
int over=0; //0 is no, 1 is yes
int valid=0;
while ( over == 0)
{
//display
cout << "\n" << ttt[0] << "|" << ttt[1] << "|" << ttt[2] <<"\n-----\n";
cout << ttt[3] << "|" << ttt[4] << "|" << ttt[5] <<"\n-----\n";
cout << ttt[6] << "|" << ttt[7] << "|" << ttt[8] <<"\n\n Choose a number (Player " << turn << "):";
//ask enter for play with turn
cin >> move;
cout << "\n";
valid = 0;
while (valid == 0)
{
//check if input is valid
if (((move > 0) and (move < 10)) and
((ttt[move-1] != 'A') and (ttt[move-1] != 'B')) and
(cin))
{
ttt[move-1] = turn;
valid=1;
}
else
{
cout << "Invalid slot. Choose a number (Player " << turn << "):";
cin >> move;
cout << "\n";
}
}
//check if done if no //change turn then goto //display
if (((ttt[0]==ttt[1]) and (ttt[1]==ttt[2])) or
((ttt[3]==ttt[4]) and (ttt[4]==ttt[5])) or
((ttt[6]==ttt[7]) and (ttt[7]==ttt[8])) or
((ttt[0]==ttt[3]) and (ttt[3]==ttt[6])) or
((ttt[1]==ttt[4]) and (ttt[4]==ttt[7])) or
((ttt[2]==ttt[5]) and (ttt[5]==ttt[8])) or
((ttt[0]==ttt[4]) and (ttt[4]==ttt[8]))or
((ttt[2]==ttt[4]) and (ttt[4]==ttt[6])))
{
//display winner or say draw
cout << "Player " << turn << " wins!\n";
over=1;
}
else
{
//change turn
if (turn=='A')
{ turn='B';
}
else
{ turn='A';
}
}
}
return 0;
}
There seem to be a bug on the code. On the part where check if input is valid the and (cin) seem to be failing.
When entering a character, (Instead of a number) it output continuously stacks of:
Invalid slot. Choose a number (Player A or B):
I tested the rest of condition without it, it was all working well. Is there a problem on the code or is this really "cin" problem? I've also tried out !(!cin) but it's the same scenario.
You must clear the fail bit from the cin stream in your else block.
When you enter a character that isn't an integer, the cin stream sets the fail bit, which you correctly check for in your if statement, but you never clear it afterward. This causes your input validity check to be false forever.
#include <limits>
...
else
{
cin.clear(); // Add this line
cin.ignore(numeric_limits<streamsize>::max(), '\n'); // And this one
cout << "Invalid slot. Choose a number (Player " << turn << "):";
cin >> move;
cout << "\n";
}
For additional information, see the documentation for std::basic_ios::clear
Update: see this question and this question for similar problems.
Essentially, you also need to tell cin to ignore whatever is in the stream or it will continually set the fail bit with its bad contents you haven't cleared yet. I modified the above snippet to work.
I've got these 2 programs for the current chapter in my C++ class that I cant seem to get to work and I dont understand why.
The first project requests
"Create a program that displays the appropriate shipping charge based on the zip code entered by the user. To be valid, the zip code must contain exactly five digits and the first three digits must be either “605” or “606”. The shipping charge for “605” zip codes is $25. The shipping charge for “606” zip codes is $30. Display an appropriate error message if the zip code entered is invalid. Use the sentinel value “X” to end the program."
#include <iostream>
#include <string>
using namespace std;
string zipCode = "";
string zip = "";
int main() {
cout << "ENTER AN X TO STOP ZIP CODE DATA ENTRY." << endl << endl;
cout << "Enter Zip Code: ";
getline(cin, zipCode);
while (zipCode != "x")
{
if (zipCode.length() == 5)
{
if (zipCode.find("605", 0))
{
cout << "Shipping charge is $25" << endl;
}
else if (zipCode.find("606", 0))
{
cout << "Shipping charge is $30" << endl;
}
else
cout << "Invalid Zip Code.";
}
else
{
cout << "Zip code must contain exactly 5 digits." << endl;
}
cout << "Enter Zip Code: ";
getline(cin, zipCode);
}
cout << endl << "End of Program.";
return 0;
}
I tried a similar structure for the second program and cant get it to work properly either.
Create a program that displays the color of the item whose number is entered by the user. All item numbers contain exactly seven characters. All items are available in four colors: blue, green, red, and white. The fourth character in the item number indicates the item number, as follows: a B or b indicates Blue, a G or g indicates Green, a R or r indicates Red, and a W or w indicates White. If the item number is not exactly seven characters display the appropriate error message. If the fourth character is not one of the valid color characters, display the appropriate error message. Use the sentinel value “X” to end the program.
#include <iostream>
#include <string>
using namespace std;
string itemCode = "";
int main() {
cout << "ENTER AN X TO STOP ITEM NUMBER DATA ENTRY." << endl << endl;
cout << "Enter Item Number: ";
getline(cin, itemCode);
while (itemCode != "x")
{
if (itemCode.length() == 7)
{
if (itemCode.find("B", 3) == "B")
{
cout << "Color is blue." << endl;
}
else if (itemCode.find("G", 3) == "G")
{
cout << "Color is green." << endl;
}
else if (itemCode.find("R", 3) == "R")
{
cout << "Color is Red." << endl;
}
else if (itemCode.find("W", 3) == "W")
{
cout << "Color is White." << endl;
}
else
cout << "Invalid color code found in item number.";
}
else
{
cout << "Item number must contain exactly 7 characters." << endl;
}
cout << "Enter Item Number: ";
getline(cin, itemCode);
}
cout << endl << "End of Program.";
return 0;
}
From glancing at your code, two obvious problems come to mind that's likely the source of your issues:
You're not checking if getline successfully grabbed the input.
Your usage of string::find's return value is wrong. You need to check for std::npos to see if there's a match or not. See here if you need more details.
For your first problem, you want something like:
while (getline(cin, zipCode) && zipCode != "x")
// ...
And removing the other getlines.
For the second, your usage should look something like:
if (zipCode.find("605", 0) != string::npos)
// ...
Your current if (zipCode.find("605", 0)) does not work because anything other than 0 or false is considered truthy. std::string::npos is typically defined as -1 which means the expression is true if the zipCode isn't found -- the opposite of your desired behavior.
My goal here is have the user pick an operand symbol before the program error checks for correct input and delivers a message as to what type of arithmetic questions will be asked. I don't really understand using char and void prototypes. This is for an assignment in which i must use and call from these specific functions for these specific actions.
These are the prototypes I need to use:
void PrintMenu ();
char GetMenuChoice ();
void TellUserAboutOp (char i);
This is what I have in int main():
PrintMenu ();
GetMenuChoice();
TellUserAboutOp (operandChoice);
This is what the functions look like so far:
void PrintMenu ()
{
cout << "What operation would you like to practice?" << endl
<< "Please type the character giving your choice after the small arrow: "
<< endl << "\t + for addition" << endl << "\t - for subtraction" << endl
<< "\t * for multiplication" << endl << "\t / for division -> ";
}
char GetMenuChoice ()
{
char chosenOperand;
cin >> chosenOperand;
while ((chosenOperand != '+') || (chosenOperand != '-') ||
(chosenOperand != '*') || (chosenOperand != '/'));
{
cout << "That's not a valid character for your choice. Please try again!"
<< endl << "Type in the character of your choice -> ";
cin >> chosenOperand;
}
return (chosenOperand);
}
void TellUserAboutOp (char i)
{
if
(i == '+')
cout << "OK, let's try 7 different questions to practice addition.";
else if
(i == '-')
cout << "OK, let's try 7 different questions to practice subtraction.";
else if
(i == '*')
cout << "OK, let's try 7 different questions to practice multiplication.";
else if
(i == '/')
cout << "OK, le's try 7 different questions to practice division.";
return;
}
The compile warning is:
48): warning C4700: uninitialized local variable 'operandChoice' used
When you call GetMenuChoice, it returns a char, which you'll want to store in the operandChoice. A function that returns a non-void type can be used like a variable of that type. So:
char operandChoice = GetMenuChoice();
will compile and clear out the uninitialized variable warning, while doing what you need. I'm sure your assignment is to understand how function returns values that you can use in assignments and other expressions like this.
You don't show the whole code of your main, but it seems you have defined a local variable operandChoice that you have not given any useful value before you use it. You probably want a line like
operandChoice = GetMenuChoice();
somewhere in your main. According to its prototype, GetMenuChoice returns a char, meaning that you can assign the result of the function to a char variable. You can also initialize operandChoice at the location where you declare it by writing
char operandChoice = GetMenuChoice();
The prototype of the function tells you its signature. The first thing (before the function name) is the return type. void is a special return type that indicates the function doesn't actually return anything. So your usage of the other functions is correct. Doing FunctionName(some arguments) just executes the function. You can do the same thing with a function that returns char (or something else), but it will throw away the result returned from the function.
Additional hint: I think you have a problem with your while condition in GetMenuChoice. The chosenOperand variable can only be equal to one of the operand characters. So at least three of your comparisons will always yield true and thus you never exit the while loop. You probably want to combine the checks for each operator in a different way than || (which means "or").
Also, there is a ; after your while loop. This will just create an endless while loop because the following block enclosed by {, } will not be considered the body of the loop. Because of the ;, the while loop has an empty body.
Fixed code, accomplishes task.
Changed GetMenuChoice(); in int main() to:
char operandChoice = GetMenuChoice();
Repaired while loop in function:
void PrintMenu ()
{
cout << "What operation would you like to practice?" << endl
<< "Please type the character giving your choice after the small arrow: "
<< endl << "\t + for addition" << endl << "\t - for subtraction" << endl
<< "\t * for multiplication" << endl << "\t / for division -> ";
}
char GetMenuChoice ()
{
char chosenOperand;
cin >> chosenOperand;
while
((chosenOperand != '+') && (chosenOperand != '-')
&& (chosenOperand != '*') && (chosenOperand != '/'))
{
cout << "That's not a valid character for your choice. Please try again!" << endl
<< "Type in the character of your choice -> ";
cin >> chosenOperand;
}
return (chosenOperand);
}
void TellUserAboutOp (char i)
{
if
(i == '+')
cout << "OK, let's try 7 different questions to practice addition." << endl;
else if
(i == '-')
cout << "OK, let's try 7 different questions to practice subtraction." << endl;
else if
(i == '*')
cout << "OK, let's try 7 different questions to practice multiplication." << endl;
else if
(i == '/')
cout << "OK, le's try 7 different questions to practice division." << endl;
return;
}
The purpose of the conditional statement is to print out a simple text based menu and then store input from the user as well as evaluate this to the condition of a loop.
If the condition was not meet, the user should be prompted to enter in a int number, that would result in the condition being true. Instead it just exits the loop.
I have tried both while and now, if loops to accomplish the task.
Here is the Code:
#include "stdafx.h"
// Namespaces
using std::cin;
using std::cout;
using std::endl;
using std::istream;
using std::iostream;
using std::ostream;
using std::string;
// Variables
const string new_game = "Start a new game";
const string continue_game = "Continue your game";
const string load_save = "Load a save";
int menu_choice = 0;
const string choice_description = "You choice to";
// MAIN Program
int _tmain(int argc, _TCHAR* argv[])
{
cout << "Welcome to The Forgotten Time" <<endl;
cout << "You have the following options" << endl;
while (menu_choice < 1 || menu_choice > 3 )
{
cout << "1." << new_game << endl;
cout << "2." << continue_game << endl;
cout << "3." << load_save << endl;
cin >> menu_choice;
}
switch (menu_choice)
{
case 1: cout << choice_description << new_game;
case 2: cout << choice_description << continue_game;
case 3: cout << choice_description << choice_description;
}
cin.ignore();
cin.get();
return 0;
}
In the end i would like to be able to combine the conditional statement in a function
and pass it through a switch statement in order to create a sentence, that evaluates the
users input and displays their choice.
Initially you set:
int menu_choice = 0;
Then you ask:
if (menu_choice < 1 || menu_choice > 4 )
The choice is smaller than 1 so the if block is entered.
You then get some user input and exit the application.
You have no loop in your code at all. Just an initial conditional statement that would return a true value because:
menu_choice=0;
and,
if(menu_choice<1 ||...)
You don't need a "return" statement, either. Put in a switch() after your if().
Also, you could just remove the second if() condition and put your whole main() content in a while() or do..while() loop.
Also, a switch is pretty efficient if you have a menu based display that takes in certain specific discrete-set of values.
Remove your if condition, instead use a do while loop.
do{
cout << "1." << new_game << endl;
cout << "2." << continue_game << endl;
cout << "3." << load_save << endl;
cin >> menu_choice;
}
while (menu_choice!=0);