if - elseif - else condition is not working as expected in the below code. The code behaves differently when passing different inputs. It looks like break is not working or being skipped in the case.
Code:
#include <iostream>
void function(){
int option;
char choice;
std::cout << "Select an option\n";
std::cin >> option;
switch (option)
{
case 1:
std::cout << "Y or N ??\n";
std::cin >> choice;
if (choice == 'Y')
{
break;
}
else if (choice == 'N')
{
function();
}
else
{
std::cout << "Error : Invalid Input1\n";
break;
}
default:
std::cout << "Error : Invalid Input2\n";
break;
}
}
int main()
{
function();
return 0;
}
output of the code when executed in a linux environment.
user@user:~/CPP_Project/test$ g++ test.cpp
user@user:~/CPP_Project/test$ ./a.out
Select an option
1
Y or N ??
Y
user@user:~/CPP_Project/test$
user@user:~/CPP_Project/test$ ./a.out
Select an option
1
Y or N ??
N
Select an option
Y
Error : Invalid Input2
Error : Invalid Input2
user@user:~/CPP_Project/test$