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;
...
Related
I am working on a little text based adventure game, the first project I've ever worked on for my own enjoyment, and have ran into a problem. I have got it to ask if you want to play, what your name will be and then the problem starts when you try to choose a race. It works just fine when the user types the first character but when they type the string it will skip past the gender, and class cin. Do I have to clear the cin? Or is my code just wrong?? Thanks for any help you can provide.
#include "pch.h"
#include <iostream>
#include <string>
#include <cctype>
#include <map>
using namespace std;
enum races { Human, Orc, Elf, Dwarf};
enum classes { Warrior, Mage, Archer, Assassin};
const std::map< char, string > race_map =
{ {'H', "human"}, {'O', "orc"}, {'E', "elf"}, {'D', "dwarf"} };
const std::map< char, string > class_map =
{ {'W', "warrior"}, {'M', "mage"}, {'Ar', "archer"}, {'A', "assassin"}
};
void gameIntro();
void gameStart();
void raceFunc(char race);
void playerClassFunc(char playerClass);
void gameIntro()
{
string playerName;
char race;
char sex;
char playerClass;
cout << "Enter your name: \n";
cin >> playerName;
cout << "\n";
cout << "Select a race (Human, Orc, Elf, Dwarf): \n";
cin >> race;
cout << "\n";
raceFunc(race);
cout << "Select Gender (M or F): \n";
cin >> sex;
cout << "\n";
cout << "Select a class (Warrior, Mage, Archer, Assassin): \n";
cin >> playerClass;
cout << "\n";
playerClassFunc(playerClass);
gameStart();
}
void raceFunc(char race)
{
race = toupper(race);
switch (race)
{
case 'H':
cout << "You chose Human!\n\n";
break;
case 'O':
cout << "You chose Orc!\n\n";
break;
case 'E':
cout << "You chose Elf!\n\n";
break;
case 'D':
cout << "You chose Dwarf!\n\n";
break;
default:
cout << "Please choose from the following. Program closing.\n";
system("pause");
exit(0);
}
}
void playerClassFunc(char playerClass)
{
playerClass = toupper(playerClass);
switch (playerClass)
{
case 'W':
cout << "You chose Warrior!\n";
break;
case 'M':
cout << "You chose Mage!\n";
break;
case 'Ar':
cout << "You chose Archer!\n";
break;
case 'A':
cout << "You chose Assassin!\n";
break;
default:
cout << "Please choose from the following. Program closing.\n";
system("pause");
exit(0);
}
}
void gameStart()
{
}
int main()
{
char answer;
cout << "Welcome to Dark Horse\n\n";
cout << "This is my fisrt ever actual program I made out of my own free
will lol.\n";
cout << "It is a Text-Based Adventure game. In this game you will make a
character,\n";
cout << "and explore the land of Spelet, battling enemies, leveling up,
getting loot,\n";
cout << "and learning skills! You do not need to capitalize anything but
your character\n";
cout << "name. If a question has (something like this) if you don't
enter whats inside\n";
cout << "the program will CLOSE, so please pay attention! Thank you for
trying it out!\n";
cout << "I really hope y'all enjoy it!\n\n";
do
{
cout << "Would you like to play?\n";
cin >> answer;
if (answer == 'Y')
{
gameIntro();
}
else if (answer == 'N')
{
system("pause");
return 0;
}
else if (answer != 'N' || 'Y' || 'exit')
{
cout << "Come on dog it's Y or N...yes or no...\n\n";
}
} while (answer == 'N' || 'Y');
system("pause");
return 0;
}
"cin, of class istream, is the standard input channel used for user input. This steam corresponds to C's stdin. Normally, this stream is connected to the keyboard by the operating system." (Josuttis, 2012, p. 745)
Josuttis, N. (2016). The C++ Standard Library: A Tutorial and Reference 2nd Edition: Addison-Wesley
The types are important.
char race;
std::cout << "Please enter your race:" << std::endl;
std::cin >> race;
If the user enters "Human", the standard input stream contains Human and the race variable now has the value H (of type char). The standard input stream now contains uman.
char gender;
std::cout << "Please enter your gender:" << std::endl;
std::cin >> gender;
Calling >> with std::cin gets another character from the standard input stream (in this case u) and stores it in gender. The standard input stream now contains man.
While it appears that the gender question was skipped, you can now see that this is not the case. The input stream still contains characters. If you look at your first screenshot you can see that "Mage" was selected. This is because the value of playerClass is m, the same m from when you entered human.
One way to remedy this is to use std::string instead of char to store the input. That way you have more flexibility in parsing what the user enters (e.g. you can allow for H or Human).
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.
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;
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.
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 12 years ago.
So usually after a night of "drinking", I come home and check the level of drunkenness by programming. I decided to make a calculator program. I got an error, and now I can't go to sleep. Can someone please remove me from this misery. What is wrong with this code?
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
double num1;
double num2;
char redo;
char operation;
do
{
cout<< "Please enter your calculation "<< endl;
cin >> num1 >> operation >>num2;
switch operation {
case '+':
cout<< "" <<num1+num2 << endl;
break;
case '/':
cout<< "" <<num1/num2 << endl;
break;
case '*':
cout<< "" <<num1*num2 << endl;
break;
case '/':
cout<< "" <<num1/num2 << endl;
break;
}
while (redo=='y'||redo=='Y');
system("PAUSE");
return EXIT_SUCCESS;
}
My first debug error is at the cout.. I haven't been able to sleep :(
YAY! I'm NOT drunk!! I got it to work!!! Thajink yoou giusy so mcuh!!
Oh, heres the code btw:
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
double num1;
double num2;
char redo;
char operation;
do
{
cout<< "Please enter your calculation "<< endl;
cin >> num1 >> operation >>num2;
switch (operation) {
case '+':
cout<< num1+num2 << endl;
break;
case '-':
cout<< num1-num2 << endl;
break;
case '*':
cout<< num1*num2 << endl;
break;
case '/':
cout<< num1/num2 << endl;
break;
}
cout<<" Do you want to continue? ";
cin>>redo; }
while (redo=='y'||redo=='Y');
}
Your program is missing a closing curly brace for the switch statement; I'm not sure if that's an error in copying the code to the post or if that's what's actually responsible for your woes.
On a somewhat unrelated note, I noticed that at a few spots in your code you've written
cout<< "" <<num1+num2 << endl;
You don't need to print the empty string before printing out the sum; you can just write
cout<< num1 + num2 << endl;
Another issue you might be having is that your code loops with this condition:
while (redo=='y'||redo=='Y');
However, your code never assigns a value to redo, so this has unspecified behavior - it could loop forever, or loop just once.
Hopefully this helps fix things up!
Which cout? You use it 5 times in your program.
You're reading redo without ever assigning a value to it. That's not likely to work right.
You seconda case should be a '-' not a '/'. There aren't enough closing parentheses.
This works for me:
#include <cstdlib>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
double num1;
double num2;
char redo;
char operation;
do
{
cout<< "Please enter your calculation "<< endl;
cin >> num1 >> operation >>num2;
switch (operation )
{
case '+':
cout<< "" <<num1+num2 << endl;
break;
case '-':
cout<< "" <<num1-num2 << endl;
break;
case '*':
cout<< "" <<num1*num2 << endl;
break;
case '/':
cout<< "" <<num1/num2 << endl;
break;
}
}
while (redo=='y'||redo=='Y');
system("PAUSE");
return EXIT_SUCCESS;
}
Some bugs I could see:
There is a missing closing brace } for switch block.
The condition in switch should be in parenthesis:
switch (operation) {
^ ^
There is duplicate case '/'. Case - is missing.
Variable redo is being used uninitialized. You need to ask user if he wants to continue. Read the response in variable redo.
See it