Condition is not evaluated in loop - c++

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

Related

How do I execute previously executed lines of code in C++

I've started to learn how to code in C++ on my spare time, using different sites and apps that someone who has also learned C++ online provided me with. By now, I know the most basic commands. I've tried an exercise given by a program, and I'm given the information that someone is going on a vacation, and needs to know how much baggage he can bring with him. The limit to how many baggages he can carry is 45, and I have to display a different output if the baggages are below, above or the same as the limit (45 baggages). I have done some coding, and I ended up with this:
#include <iostream>
using namespace std;
int main()
{
const int limit = 45;
int bag;
cout << "Please type your number here: ";
cin >> bag;
string yn;
int keep = 0;
if (limit < bag)
{
cout << "You passed the limit." << endl;
};
if (limit == bag)
{
cout << "Just enough." << endl;
};
if (limit > bag)
{
cout << "You got space." << endl;
};
++keep;
while(keep > 0)
{
int keep = 0;
cout << "Do you want to try another number?" << endl;
cin >> yn;
cout << endl;
if(yn == "yes")
{
int bag = 0;
cout << "Please type your number here: ";
cin >> bag;
if (limit < bag)
{
cout << "You passed the limit." << endl;
};
if (limit == bag)
{
cout << "Just enough." << endl;
};
if (limit > bag)
{
cout << "You got space." << endl;
};
}
else
{
return 0;
}
}
}
I have developed it more than needed -as you can see-, out of my own interest in the problem. I have copied and pasted the 3 IF commands as seen above, and I believe that there is an easier way, with less code, do solve this. What I have thought of is if I could go back and execute some line of code again, either from a line and below (e.g. from line 45 and below), or specific lines of code (e.g. from line 45 to line 60).
I would appreciate it if you thought of another way to solve this problem and posted your code below.
Thank you for your reply.
We all started writing our first C++ program at some time, so allow me to give you some additional feedback:
First of all, avoid writing using namespace std;
Secondly, naming - what is bag, limit, keep and yn? Wouldn't it be much easier to read and understand if they were called bagSize, maximumPermittedBagSize, inputFromUser (you don't really need the variable keep, see below)?
Finally, here is a (roughly) refactored version your program, with duplication removed and comments added.
#include <iostream>
int main()
{
const int maximumPermittedBagSize = 45;
// Loops forever, the user exits by typing anything except 'yes' laster
while(true)
{
std::cout << "Please type your number here: " << std::endl;
//Declare (and initialize!) variables just before you need them
int bagSize = 0;
std::cin >> bagSize;
if (bagSize > maximumPermittedBagSize)
{
std::cout << "You passed the limit." << std::endl;
}
else if (bagSize == maximumPermittedBagSize )
{
std::cout << "Just enough." << std::endl;
}
else
{
std::cout << "You got space." << std::endl;
}
std::cout << "Do you want to try another number?" << std::endl;
std::string inputFromUser = "";
std::cin >> inputFromUser;
std::cout << std::endl;
//Leave the loop if the user does not answer yes
if(inputFromUser != "yes")
{
return 0;
}
}
}
You can simply run a while loop and do like this:
#include <iostream>
using namespace std;
int main()
{
const int limit = 45;
int bag;
string yn = "yes";
while(yn == "yes")
{
cout << "Please type your number here: ";
cin >> bag;
if (limit < bag)
{
cout << "You passed the limit." << endl;
}
else if (limit == bag)
{
cout << "Just enough." << endl;
}
else if (limit > bag)
{
cout << "You got space." << endl;
}
cout << "Do you want to try another number?" << endl;
cin >> yn;
cout << endl;
}
}

Trying to condition my do-while to stop exiting program in terminal. Menu does not loop in while as desired with current statements

I have an issue with my do-while loop where it will exit the program no matter the input or my statements in while.
I'VE TRIED CHANGING
while(menureturn > '4' || menuselect < '1');"
TO
while(menureturn > '4' && menuselect < '1');
HERE IS THE SOURCE CODE MY PROJECT
#include <iostream>
#include <string>
using namespace std;
int choice, menuselect;
char menureturn;
int menu() {
cout << "1. Math Menu" << endl;
cout << "2. Currency Conversion" << endl;
cout << "3. Cryto Currencies" << endl;
cout << "4. Display Time Zone selection" << endl;
cout << ":" << endl;
cin >> menuselect;
return menuselect;
}
int main()
{
do {
menu();
} while(menureturn > '4' && menuselect < '1');
return 0;
}
MY OUTPUT
1. Math Menu
2. Currency Conversion
3. Cryto Currencies
4. Display Time Zone selection
:
6
C:\Users\Gage\source\repos\Menu\Debug\Menu.exe (process 35580) exited with code 0.
To automatically close the console when debugging stops, enable Tools->Options->Debugging->Automatically close the console when debugging stops.
Press any key to close this window . . .
Your problem was that you were comparing if an int number, was the same as char when you put ' ' around your numbers.
} while(menureturn > '4' && menuselect < '1');
And you did not assign menureturn to any value which just leaves it being null and doesn't contain a value, and therefore should not be used in a condition.
So this can be fixed very simply by first not comparing in the Do-While-Loop using a char but rather by using an int. Then we can simply just assign the menu() function to an int - since that is the return type and just compare that value
#include<iostream>
#include<string>
using namespace std;
// choice variable
int choice;
// the menu function
int menu()
{
cout << "1: Do Something" << endl;
cout << "2: Do Something" << endl;
cout << "3: Do Something" << endl;
cout << "4: Do Something" << endl;
cout << ":" << endl;
cin >> choice;
return choice;
}
int main()
{
// declare an empty int
int output;
do
{
// assigning the int to
// return value of menu()
output = menu();
} while(output > 0 && output < 5)
// Do Something Else
}
Note
using || in a condition will return as soon as one of the statements are true or false. Where as && will only return if all the statements are either true or false in the condition.
Or, are you looking for another form of answer?

Conditional cin giving stacked cout messages

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.

Menu Structure and Loops

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

Do/While loop not looping

I am a beginner in C++ and I was doing a do/while loop exercise and I am having trouble with it recognising the condition let alone it not looping properly. Can you guys give me a good foundation on how a simple problem like this is solved? I want to try and use a string to fulfill the condition of the do/while loop.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main ()
{
double mean = 0;
string continuer;
do
{
cout << "Do you want to proceed?" << endl;
getline (cin, continuer);
cout << "something" << endl;
cin >> mean;
}
while (continuer == "Y" || continuer == "y");
return 0;
}
What I gather from your question and comment, you want to iterate through the loop at user's will.
You just want a char variable for that, like this.
string input ;
int number = 0 ;
do
{
cout << "Please enter a number" << endl ;
cin >> number ;
cout << "If you want to continue, Press Y" << endl ;
cin >> input ;
} while (input == "Y" || input == "y") ;
This do-while loop will execute at least one time, because the condition gets checked at the end of the loop execution. So even if the user does not press Y when asked the first time, this loop would have been executed once. After that, it will go on as long as the condition is fulfilled.
Learn more about the do-while loop here.
http://www.cplusplus.com/doc/tutorial/control/
What do you see? The body of the loop should be executed at least once. Does that happen?
Also, Continuer can be longer than one character, for instance "Y\n". Do test for that.
Here is what I would do:
#include <string>
#include <sstream>
using namespace std;
int main ()
{
double number = 0;
string continuer;
int loop = 0
do
{
cout << "Do you want to proceed?" << endl;
getline (cin, number);
cout << "something" << endl;
cin>> mean;
getline (cin, continuer);
cout << "Your answer was '" << continuer << "'." << endl;
loop = strcmp("Y", continuer);
if (loop != 0) strcmp("y", continuer);
if (loop == 0) cout << "Your choice is to stop." << endl;
else cout << "Your choice is to continue." << endl;
} while (loop == 0);
cout << "Bye" << endl;
return 0;
}
Be as explicit as you can untill you are confident enough in the language and the algorithm you are working with. It is easier to see what is happening and when it works it is easy to remove the 'cout' lines.