Multiple if-else in C++ - c++

I am getting confused with a simple program of multiple if-else in c++. The code
is given below.
include<iostream.h>
void main()
{
int i;
cout<<"Enter the number:";
if(i==1)
{
cout<<"Sunday";
}
if(i==2)
{
cout<<"Monday";
}
else
{
cout<<" invalid input";
}
}
When I try to run this code ,the output shows this.
Enter the number:1
Sunday invalid key
So my question is why the output executing the Else part though the output is True..? Please help me . Thank You

This is because you don't have "multiple if-else", really. You have a single if (without else), then another if. The two are independent. You probably wanted:
if(i==1)
{
cout<<"Sunday";
}
else if(i==2)
{
cout<<"Monday";
}
else
{
cout<<" invalid input";
}
This makes sure the final else block only runs if none of the preceding conditions are met.

First you check whether i equals one. If it is the case, "Sunday" is printed. The if statement is finished at that point. Afterwards you check (in a separate if statetement) whether i equals two, you print "Monday" if it is the case, or "invalid input" if it is not the case. To obtain the result you want, write
else if (i == 2)
to have the second if/else statement only executed if i is not 1.
Alternatively, you might want to use a switch statement.
switch(i)
{
case 1:
cout << "Sunday";
break;
case 2:
cout << "Monday";
break;
default:
cout << "invalid input";
break;
}
But don't forget the breaks if using switch!

You have to put else if, if you wanna have the right processing:
if(i==1)
cout<<"Sunday";
else if(i==2)
cout<<"Monday";
else
cout<<" invalid input";
With else if, the second and the third condition are not processed, because the first one is alredy valid. In your code, it is first processed the code under the first condition, than because the input is not equal to 2, the code under the else is processed.

There are several bugs in this code. I explained and fixed it here-
#include<iostream.h>
void main()
{
int i;
cout<<"Enter the number:";
cin >> i; //take the input number from the user
if(i==1)
{
cout<<"Sunday";
}
/* the i==1 and i==2 block will run separately unless you connect them with an else */
else if(i==2)
{
cout<<"Monday";
}
else
{
cout<<" invalid input";
}
}

This is cause you have used two branching statement for same input
1. The first if() statement check if your value is equal 1 or not
if(i == 1)
std::cout << "Sunday"; // here you have print "Sunday for 1
2. Then again you check your value with another if-else statement
if(i == 2)
std::cout << "Mondey";
else
std::cout << "invalid input"; // here you have print "invalid input"
//since i is not equal to 1

You have two different conditions. One is:
if(i==1) {
cout<<"Sunday";
} // this statement ends here.
The other:
if(i==2) {
cout<<"Monday";
} else {
cout<<" invalid input";
}
The second is always going to result " invalid input" when i is not 2.

Related

C++: Telling user to input A, B, or C but what if they enter a different character?

As the title suggests, I have a working program for when a user inputs A B or C. My professor has said that we have not gone over repetition yet so we just need to put in a line of code that returns something like "Please enter either A B or C" when the user enters any other character but I am having trouble figuring out how to do this. Any help will be very appreciated. I'll post a file of the code I have now.
https://docs.google.com/document/d/1EVxLPtOsBbdmCCt0LwUDYkqgySg8bSm3w_d_CAcGW6g/edit?usp=sharing
Here is a common stencil for processing menus:
bool invalid_selection = true;
while (invalid_selection)
{
// Output the menu with choices
// ...
char choice;
std::cin >> choice;
choice = std::toupper(choice);
switch (choice)
{
case 'A':
do_something;
break;
// ... other choices ...
default:
std::cout << "Invalid choice.";
}
if (choice == quit_character)
{
break; // exit out of the loop
}
}
There are many other alternatives. For example, one is a do-while loop.
If you don't know about switch, use your if-else-if ladder. The final else clause is equivalent to the default case.
EDIT: It'd be even better to use a std::string as a buffer to prevent receiving multiple errors from this if the user inputs more than one char.
The best way to handle this would probably be a simple do... while nested switch statement:
#include <string>
bool repeat = true;
do {
std::string buffer;
cout << "Which plan do you want to use?" << endl;
cin >> buffer;
// check if the user entered only one character
if (buffer.length() > 1) {
cout << "Invalid Input" << endl;
continue;
}
plan = buffer[0];
switch(plan) {
case 'A':
// do things
repeat = false;
break;
case 'B':
// do things
repeat = false;
break;
case 'C':
// do things
repeat = false;
break;
default:
cout << "Invalid input, please try again." << endl;
break;
} while (repeat);
This keeps asking the user for which plan they want to use, until you receive valid input.
Note: OP did not want a complete refactoring of his code. So this is the minimal-intervention solution.
Edit your if statements to:
if(plan=='A'){
//...
} else if(plan=='B'){
//...
} else if(plan=='C'){
//...
} else {
//handle the error here.
cout << "Wrong input" << endl;
}

C++. If Statement won't exit

I have a function with a while loop and some if statements in it, everything runs as expected, however, when the If statement that should return the vector select_control value runs, it doesn't terminate the function after returning a value.
vector<int> select() {
vector<int> select_control;
int select;
cin >> select;
while (select < 10) {
//SOME CODE THAT PUSHES VALUES INTO THE VECTOR select_control
}
if (select == 99){
cout << "TERMINATING";
Sleep(3000);
exit(0);
}
else if (select == 100) {
cout << "input complete";
return select_control;
}
else {
cout << "not a valid value";
}
}
Rather than exit(0); in your conditional statement, put a break;.
Use the break; syntax. This exists out of the if stement, you don't have to include anything.
Well for starters your loop never ends because select never gets updated for the loop to eventually become false, you can add a break; after it does return select_control or you can just do exit(0); if there's absolutely nothing else the program is gonna do. You should also add break; or exit(0) after cout << "not a valid value"; because select isn't being updated for the while loop to become false and exit.

how to create message when loop completed

I have a code working on basic c++. I just want when this loop become completed and one if statement become true, a message generate automatically. In this regard i have used while statement but while statement is also work i don't want to display the message. Means when if statement (congratulation....) become true, the message (You don't have more...) displays.
for(i=1; i<=attempt; i++){
cout<< "whatever" ;
cin >> userNumber;
if (userNumber < secretNumber){
cout << "Oooppssss... Your entered number is too low..." <<endl;
}
else if (userNumber > secretNumber){
cout << "Oooppssss... Your entered number is too high..."<<endl;
}
else if(userNumber==secretNumber){
cout << "Congratulation you have won..."<<endl;
break;
}
else{
cout << "Invalid Input."<<endl;
}
}
while(attempt=i){
cout<< "You don't have more turn...Computer Won."<<endl<<endl;
break;
}
Reason is you are not using == and hence condition always turns true. Also instead of while loop you need if
while(attempt=i){
Use
if((attempt + 1) == i){

How to prevent the user from entering more than one character in the below sample code?

I am facing problem in the below code. If the user enter more than one charater then my loop gets executed number of times equal to the length of the string entered by the user. My code is written in GNU c/c++ compiler.
Thanks in advance.
int continue_option()
{
char c;
loop:
fflush(stdin);
cin.ignore();
cout<<"\n\n\t\t\t\tPress (Y/y) - Continue / Press (N/n) - Exit :";
cin>>c;
if(c=='y'||c=='Y')
{
system("clear");
}
else if(c=='n'|| c=='N')
{
exit(0);
}
else
{
printf("\n\t\t\t\tInvalid Option.Try Again.....");
goto loop;
}
fflush(stdin);
}
First thing, don't use jumps. They are old style, and they make Dijkstra spin in his grave, on top of all the other bad consequences. I don't mean "vintage", I really mean old in the bad sense.
As of your question, I'd rather put the result in a std::string and only consider the first character in there:
std::string input;
std::cin >> input;
switch (input[0]) {
case 'y':
case 'Y':
//your code
break;
case 'n':
case 'N':
exit(0);
default:
std::cout << "Invalid text" << std::endl;
}
I would also refrain from using exit(), I'd rather rely on a function's return value to finally cause a return 0; in the main(), or some equivalent technique.
You can't stop the user from typing more than one character.
What you can do is ignore the rest of the line. You have already use cin.ignore() which ignores one character. You can use cin.ignore(large number) to ignore up to the large number or the end-of-line, whichever appears first.
Unlike flushing output files, fflush(stdin) doesn't really do anything.
Try using cin.get() or getch() to read just one character at a time. Also, I guess you'd be better off replacing the whole thing with a simple loop like:
char ch = '\0';
do
{
ch = getch();
}while((tolower(ch) != 'y') || (tolower(ch) != 'n'))
if(tolower(ch) == 'y')
{
//additional handling
}
else
{
exit(0);
}
Not exactly the same behavior, but should put you on track:
#include <iostream>
#include <iomanip>
bool is_valid_answer(char c)
{
switch(c)
{
case 'y':
case 'Y':
case 'n':
case 'N':
return true;
default:
return false;
}
}
bool continue_option()
{
std::cout << "Press (Y/y) to continue, (N/n) to exit: " << std::flush;
char c = '\0';
while (std::cin.get(c) && !is_valid_answer(c));
return ((c == 'y') || (c == 'Y'));
}
int main()
{
std::cout << "Continue option: " << continue_option() << std::endl;
}

Advanced switch statement within while loop?

I just started C++ but have some prior knowledge to other languages (vb awhile back unfortunately), but have an odd predicament. I disliked using so many IF statements and wanted to use switch/cases as it seemed cleaner, and I wanted to get in the practice.. But..
Lets say I have the following scenario (theorietical code):
while(1) {
//Loop can be conditional or 1, I use it alot, for example in my game
char something;
std::cout << "Enter something\n -->";
std::cin >> something;
//Switch to read "something"
switch(something) {
case 'a':
cout << "You entered A, which is correct";
break;
case 'b':
cout << "...";
break;
}
}
And that's my problem. Lets say I wanted to exit the WHILE loop, It'd require two break statements?
This obviously looks wrong:
case 'a':
cout << "You entered A, which is correct";
break;
break;
So can I only do an IF statement on the 'a' to use break;? Am I missing something really simple?
This would solve a lot of my problems that I have right now.
I would refactor the check into another function.
bool is_correct_answer(char input)
{
switch(input)
{
case 'a':
cout << "You entered A, which is correct";
return true;
case 'b':
cout << "...";
return false;
}
return false;
}
int main()
{
char input;
do
{
std::cout << "Enter something\n -->";
std::cin >> input;
} while (!is_correct_answer(input));
}
You could simply have the while loop check for a bool value that is set within one of your case statements.
bool done = false;
while(!done)
{
char something;
std::cout << "Enter something\n -->";
std::cin >> something;
//Switch to read "something"
switch(something) {
case 'a':
cout << "You entered A, which is correct";
done = true; // exit condition here
break;
case 'b':
cout << "...";
break;
}
}
Yes, C and C++ have no way to say "exit multiple breakable blocks" (where a "breakable block" is any loop or switch). Workarounds include gotos and use of boolean variables to record whether an outer "breakable block" should also break (neither is elegant, but, that's life).
Two break statements will not get you out of the while loop. The first break only gets you out of the switch statement and the second one is never reached.
What you need is to make the condition of the while loop false, assuming that there is nothing in the loop after the switch statement. If there is other code after the switch, you should check the condition after the switch, and break there.
bool done = false;
while(! done)
{
// do stuff
switch(something)
{
case 'a':
done = true; // exit the loop
break;
}
// do this if you have other code besides the switch
if(done)
break; // gets you out of the while loop
// do whatever needs to be done after the switch
}
You could try:
Using Flags
Using Goto
Having the Inner Breakable block into a function
Using Exceptions
Using longjump and setjmp
A topic very similar to this question
http://www.gamedev.net/community/forums/topic.asp?topic_id=385116
You might be interested in the named loop idiom in C++.
#define named(blockname) goto blockname; \
blockname##_skip: if (0) \
blockname:
#define break(blockname) goto blockname##_skip;
named(outer)
while(1) {
//Loop can be conditional or 1, I use it alot, for example in my game
char something;
std::cout << "Enter something\n -->";
std::cin >> something;
//Switch to read "something"
switch(something) {
case 'a':
cout << "You entered A, which is correct";
break(outer);
case 'b':
cout << "...";
break(outer);
}
}
You can also encapsulate the loop into a function and call return inside the case, for the case that the flag breaking the while is not enough.
It is not a good programming practice for some people but if you keep the function simple I don't see why not.
You could replace the switch with a slightly over-engineered OO solution...
#include <iostream>
#include <map>
#include <set>
class input_responder
{
std::set<char> correct_inputs;
std::map<char, const char*> wrong_inputs;
public:
input_responder()
{
correct_inputs.insert('a');
wrong_inputs['b'] = "...";
}
bool respond(char input) const
{
if (correct_inputs.find(input) != correct_inputs.end())
{
std::cout << "You entered " << input << ", which is correct\n";
return true;
}
else
{
std::map<char, const char*>::const_iterator it = wrong_inputs.find(input);
if (it != wrong_inputs.end())
{
std::cout << it->second << '\n';
}
else
{
std::cout << "You entered " << input << ", which is wrong\n";
}
return false;
}
}
};
int main()
{
const input_responder responder;
char input;
do
{
std::cout << "Enter something\n -->";
std::cin >> input;
} while (responder.respond(input) == false);
}
You could change your switch to an ifsystem. It will be compiled to the same thing anyway.