Loop in a switch case statement - c++

I need help with validating a switch case statement i need it to check what the user has entered and if it does not match reject it and tell them to do it again. the one i have at the moment partially works but will reject the first number then break when trying to enter another number. Help If you need to see the whole program just ask.
#include "stdafx.h"
#include "cstdlib"
#include "iostream"
#include "windows.h"
#include "cmath"
using namespace std;
int main(int argc, char* argv[])
{
float ALT0();
float ALT5000();
float ALT10000();
float ALT15000();
float ALT20000();
float ALT25000();
float ALT30000();
float ALT35000();
float ALT40000();
void an_answer(float a);
char Restart;
char op;
float answer;
do
{
cout << "\n\t\t\tOperational Flight Plan\n" << endl;
cout << "For the saftey of everyone on board, there will be 100 kg added to the overall\namount to give the aircraft more fuel incase of a head on wind or delays at the landing airport.\n" << endl;
cout << "Select Altitude the aircraft will fly at: " << endl;
cout << "0 for 0ft\n1 for 5000ft\n2 for 10000ft\n3 for 15000ft\n4 for 20000ft\n5 for 25000ft\n6 for 30000ft\n7 for 35000ft\n8 for 40000ft" << endl;
cin >> op;
switch (op)
{
case'0':
answer=ALT0();
break;
case '1':
answer=ALT5000();
break;
case '2':
answer=ALT10000();
break;
case '3':
answer=ALT15000();
break;
case '4':
answer=ALT20000();
break;
case '5':
answer=ALT25000();
break;
case '6':
answer=ALT30000();
break;
case '7':
answer=ALT35000();
break;
case '8':
answer=ALT40000();
break;
default:
cout << "You must enter a number from 0-8" << endl;
cin >> op;
break;
}
an_answer(answer);
cout << "Do you want to do another calculation? Press Y for yes and anything else to quit.";
cin >> Restart;
} while (Restart=='y' || Restart=='Y');
//system("PAUSE");
//return EXIT_SUCCESS;
}

I'm betting you're hitting enter after entering the number. Your first cin >> op reads the number, but your second one reads the enter key. If you want to read in an entire line, use a function that reads in an entire line.
Alternately, move the second cin >> op up to before the switch statement. This will break if someone enters more than one character before hitting enter but will work otherwise.

Related

Why is my program skipping right over my cin, and going directly to default in a switch?

I have been trying to fix this issue for quite a while, and I have no clue where I am going wrong. I am not receiving any syntax errors, but I am not sure if I am making a basic mistake.
#include <iostream>
#include <cmath>
#include <string>
#include <unistd.h>
using namespace std;
/* Starting code below! */
int main() {
char name;
int damage;
int health;
int agility;
cout<<"\u2694 Welcome to open world RPG \u2694 \n \n";
cout<<"Welcome traveller! What is your name? \n \n";
cin>>name;
sleep(1);
cout<<"==========Character Custimization========== \n \n";
cout<<"1) Golem, 2) Adventurer, 3) Knight, 4) Hare-Morph \n \n";
int profile;
cin>>profile;
switch (profile) {
case '1':
cout<<"You have chosen Golem!" << endl;
break;
case '2':
cout<<"You have chosen Adventurer!" << endl;
break;
case '3':
cout<<"You have chosen Knight" << endl;
break;
case '4':
cout<<"You have chosen Hare-Morph!" << endl;
break;
case '5':
cout<<"DEBUG PLAYER" << endl;
break;
default:
cout<<"FAILED INPUT";
break;
}
exit(0);
}
I am expecting a user input question, with my program following with an answer from the switch.

C++ received char for integer type cause switch case went wrong

I'm trying to write a simple program that will prompt user to input a number, then it will reply back to user that which number key has been key in. Inputs other than 0~9 should go to default case which has "Not allowed." message will be print as output. The following code:
#include <iostream>
#include<cstdio>
using namespace std;
int main()
{
int x;
cout << "Please enter number from 0~9: ";
cin >>x;
switch (x)
{
case 0: cout<< "0 is pressed.";break;
case 1: cout<< "1 is pressed.";break;
case 2: cout<< "2 is pressed.";break;
case 3: cout<< "3 is pressed.";break;
case 4: cout<< "4 is pressed.";break;
case 5: cout<< "5 is pressed.";break;
case 6: cout<< "6 is pressed.";break;
case 7: cout<< "7 is pressed.";break;
case 8: cout<< "8 is pressed.";break;
case 9: cout<< "9 is pressed.";break;
default : cout << "Not allowed.";
}
return 0;
}
So when I try to input non-integer such as 'a' or "abc", it will run the statement in case 0, instead of case default. Can anyone explain why? Isn't when an integer variable trying to store a character, it would take it's ascii as it's value? Hopefully someone are willing to explain the logic behind this. Thank you!
(I'm currently using getchar() and declaring variable x as char data type, as well as case '0' and so on to temporarily solve this problem. But I myself is interesting to learn the knowledge about this. Sorry if such post is duplicated, I tried to search and found none. Wish that my searching technique isn't that terrible.)
This is introduced in c++11, if std::cin extraction fails x is zero initialised.
If extraction fails, zero is written to value and failbit is set. If
extraction results in the value too large or too small to fit in
value, std::numeric_limits::max() or std::numeric_limits::min()
is written and failbit flag is set.
Obviously providing a letter when number is expected leads to extraction failure.
If you are not using c++11 and above then the value of x is whatever it was before the operation.
What you can do to rectify this is to read a char instead and compare it to char as well:
char x;
cout << "Please enter number from 0~9: ";
cin >> x;
switch (x)
{
case '0': cout << "0 is pressed."; break;
case '1': cout << "1 is pressed."; break;
//..the rest of cases..//
default: cout << "Not allowed.";
}
Alternatively, you could handle extraction failure and clear std::cin then prompt the user again:
#include <iostream>
#include <limits>
int main()
{
int x;
while (true)
{
std::cout << "Please enter 1, 22 or 155: ";
if (std::cin >> x)
break;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
switch (x)
{
case 1: std::cout << "1 is entered\n"; break;
case 22: std::cout << "22 is entered\n"; break;
case 155: std::cout << "155 is entered\n"; break;
default: std::cout << x << " is not an option, good bye!\n";
}
return 0;
}
Let me try to break it down:
int x; // will store 0 in x as it is the default value of int
cout << "Please enter number from 0~9: ";
cin >>x; // if you input a string this will fail, and cin should be in an error state,
// and the value of x is unchanged
switch (x)
{
case 0: cout<< "0 is pressed.";break; //< x is 0
...
You should check if cin has error'd in order to handle strings:
if (cin.fail()) {
//handle error
cin.clear() // reset cin error flags
}
once different type data enter in "cin" it takes default value of that type.
int x;
cout << "Please enter number from 0~9: ";
cin >>x;
input comes string, it return 0 as default value of int x.

Switch Case always goes to default

I am trying to make a small operating system that takes a response from a switch...case to go to a miniature game or a simple calculator. However, no matter what input I give (even correct ones) the output is always the default.
The compiler I am using (Microsoft Visual Studio; It could be the problem) isn't giving me any errors, and I can't find or think of any mistakes. Do some of you people who are actually good at this have any answers to my problem?
#include "stdafx.h"
#include <iostream>
#include <limits>
using namespace std;
int calc() {
char op;
float num1, num2;
cout << "Enter operation:";
cin >> op;
cout << "Enter two numbers:";
cin >> num1 >> num2;
switch (op)
{
case '+':
cout << num1 + num2;
break;
case '-':
cout << num1 - num2;
break;
case '*':
cout << num1 * num2;
break;
case '/':
cout << num1 / num2;
break;
default:
cout << "That is not an operation";
break;
}
return 0;
};
int main()
{
char answer;
cout << "Welcome to the FR Operating System. \n";
cout << "If you want to go to the calculator, type in 'Calc'. \n";
cout << "If you want to go to the game, type in 'Game'. \n";
cin >> answer;
switch (answer) {
case 'Calc' || 'calc':
cout << "Welcome to the calculator. \n";
break;
case 'Game':
cout << "Welcome to our game, 'A Day in the Life'. \n";
break;
default:
cout << "That is an invalid answer. This has caused the system to crash. \n";
break;
}
atexit([] { system("PAUSE"); });
return 0;
}
'Game' is not a valid string
Even if you replace it by "Game", which is a valid string, switch doesn't work with strings.
So either use single chars in your switch or use if-else blocks where you compare std::strings via ==.
std::string answer;
cin >> answer;
if (answer == "Calc" || answer == "calc")
//...
else if (answer == "Game")
//...
else
// invalid
Use map to item callbacks
Ideally, it would be better to map item menu to it's respective actions. std::map<std::string, std::function<void()>> allows exactly that! Read the inline comments to make sense of the rest:
#include <string>
#include <map>
#include <iostream>
#include <functional>
int main()
{
std::map<std::string, std::function<void()>> menu_items;
menu_items.emplace("calc", [](){std::cout << "calculate chosen\n";}); //use lambdas to spare boilerplate
menu_items.emplace("game", [](){std::cout << "game is chosen\n";});
std::string chosen_item;
std::cin >> chosen_item;
auto item = menu_items.find(chosen_item); //search by the string
if (item == menu_items.end()) //item was not found in the list
std::cout << "invalid item is chosen\n";
else
item->second(); //execute the stored function
}
Demo.
Depending on your usage you might want to use void*() for std::function<void()>, and std::unordered_map for std::map. For your usage case it doesn't seem to matter though.
Also you might want to normalize the input, e.g. lowercase the string, or perform some other normalization. Since this is not performance sensitive part of the code, I believe overhead of std::function and std::map won't matter in this case.
You are prompting user for a string while your variable answer is a char, change your prompts to characters like c and g thus make it more convenient, thus you can use and enumerate characters in your switch / case statement:
int main()
{
char answer;
cout << "Welcome to the FR Operating System. \n";
cout << "If you want to go to the calculator, type in 'c'. \n";
cout << "If you want to go to the game, type in 'g'. \n";
cin >> answer;
switch (answer) {
case 'c':
case 'C':
cout << "Welcome to the calculator. \n";
break;
case 'g':
case 'G':
cout << "Welcome to our game, 'A Day in the Life'. \n";
break;
...

How to add char directly after (cin) in c++

I am trying to add a percent sign directly after a users input (so that the user doesn't have to type the percent symbol). When I try this, it either goes to the next line or doesn't work at all.
What I want: _%
// the blank is for the user's input.
Sorry if this is messy, I'm not sure how to add c++ here.
Here are some things that I have attempted:
// used a percent as a variable:
const char percent = '%';
cout << "Enter the tax rate: " << percent; // obviously here the percent
symbol goes before the number.
double taxRate = 0.0;
cin >> taxRate >> percent; // here I tried adding it into the cin after the cin.
cin >> taxRate >> '%'; // here I tried adding the char itself, but yet another failed attempt...
So, is it even possible to do what I am wanting?
It is definitely possible, however iostream does not really provide a proper interface to perform it. Typically achieving greater control over console io requires use of some platform-specific functions. On Windows with VS this could be done with _getch like this:
#include <iostream>
#include <string>
#include <conio.h>
#include <iso646.h>
int main()
{
::std::string accum{};
bool loop{true};
do
{
char const c{static_cast<char>(::_getch())};
switch(c)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
{
// TODO limit accumullated chars count...
accum.push_back(c);
::std::cout << c << "%" "\b" << ::std::flush;
break;
}
case 'q':
{
loop = false;
accum.clear();
break;
}
case '\r': // Enter pressed
{
// TODO convert accumullated chars to number...
::std::cout << "\r" "Number set to " << accum << "%" "\r" "\n" << ::std::flush;
accum.clear();
break;
}
default: // Something else pressed.
{
loop = false;
accum.clear();
::std::cout << "\r" "oops!! " "\r" << ::std::flush;
break;
}
}
}
while(loop);
::std::cout << "done" << ::std::endl;
return(0);
}
I have been having the same prob but I found an alternative, it doesn't automatically put % sign but it can let you add the %sign right after the cin without messing up when you run the code :> this is my homework, hope it helps as an example:
enter image description here
and here's what the output looks like:enter image description here
//Program that computes the total amount of savings after being invested
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int main()
{
char percent [1];
float IR, IRp, TC, P, I, A;
cout << "Investment Rate:" << setw(10) << left << "";
cin>> IR >> percent;
IRp = IR*.01;
cout << "Times Compounded: " <<setw(10)<<""; //TC
cin>> TC;
cout<<"Principal:" << setw(13) << right << "$"; //P
cin>> P;
A = P*(pow(1 + (IRp/TC), TC));
I=A-P;
cout<<"Interest: " <<setw(15)<<"$ " <<fixed<<setprecision(2)<<I<<endl;
cout<< "Amount in Savings:" <<setw(5)<<"$"<<fixed<<setprecision(2)<<A<<endl;
return 0;

How to make an exit in switch case implementation with user prompt?

I've a basic computing program, in it I want that when a user wants to just quit the program in his very first input without making any calculation, the program just exits. But rather here if the user enters q for quit/exit in his first input the programs runs into an infinite loop. Is there any way to provide user with some single exit key which when entered anytime(by the user) during runtime just quits the program. The innermost while loop works fine unless the outermost loop stops working.
#include "std_lib_facilities.h"
int main() {
double x = 0, y = 0, result = 0;
string operation = " ";
char op = ' ';
cout << "\nInput (e.g. -> 5*6)\nPress q to quit.\n";
while(1) {
cin >> x >> op >> y;
switch(op) {
case '+':
result = x + y;
operation = "sum";
break;
//Other switch cases
case 'q':
exit(1);
default:
cout << "Invalid input.";
break;
}
cout << "The " << operation << " of " << x << " and " << y << " is "
<< result << ".\n\n"
<< "If you have another input, press any character to continue..\n"
<< "Else press q to quit.\n";
// exit or continue program loop
while(cin >> op) {
if(op=='q' || op=='Q')
exit(1);
else
cout << "Provide next set of inputs.\n";
break;
}
}
}
If the user enter q on the first try then the stream will try to read this value to x which is a double which will fail and the state of the stream will be set to fail, after that no other I/O operation will be successfully performed and the loop will run infinitely.
You could probably check for the state of the stream just before you ask the user to continue or quit and clear the stream state if the previous operation was failed:
if(cin.fail())//check if the previous read operation failed
cin.clear();//clear the stream state,so the next cin will read what is in the buffer
while(cin >> op)
...//your other code
Try this:
boolean quit = FALSE;
while (!quit)
{
...
switch (op)
{
case 'q':
quit = TRUE;
break;
}
}
#include<iostream>
#include<stdlib.h>
using namespace std;
int main()
{
char ch;
while(true)
{
cout<<"l.print l "<<endl<<"c.print c "<<endl<<"q. exit"<<endl;
cout<<"enter choice"<<endl;
cin>>ch;
switch(ch)
{
case 'l':
cout<<"You have typed l "<<endl;
break;
case 'c':
cout<<"You have typed c"<<endl;
break;
case 'q':
cout<<"Exit ..." <<endl;
exit(0);
default:
cout<<"Wrong choice "<<endl;
}
}
return 0;
}