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;
...
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.
#include <iostream>
#include <cmath>
#include <string>
using namespace std;
int main()
{
char terminate;
double a, b, answer;
char operators;
cout << "Please enter your expression: ";
terminate = cin.peek();
cin >> a >> operators >> b;
while (terminate != 'q')
{
switch(operators)
{
case '+':
answer = a + b;
break;
case '-':
answer = a - b;
break;
case '*':
answer = a * b;
break;
case '/':
answer = a / b;
break;
case '^':
answer = pow(a,b);
break;
}
cout << a << " " << operators << " " << b << " = " << answer << endl;
cout << "Please enter your expression: ";
cin.clear();
terminate = cin.peek();
cin >> a >> operators >> b;
}
return 0;
}
This is my simple calculator program, it is meant to repeat and ask the user to enter a binary expression until the value "q" is entered, however upon entering "q" the while loop still executes once more even though the variable terminate has the value of "q". I don't understand why it is doing this, any help would be appreciated. Thanks
Let us take a look at an example of what is happening with this input:
1 + 1 Enter
terminate = cin.peek();
This line will peek into the buffer, read what is there but it will not remove it from the buffer
cin >> a >> operators >> b;
This line will read 1 + 1 and store it in a operators b and remove those characters from the buffer
Now what you have left is the Enter key which is still in the buffer and it will be read the next time you try and read the buffer and this is where you issue is as the next time you call terminate = cin.peek(); you get the \n and not the q that you expect
I noticed that you might have tried to fix that issue by calling std::cin::clear but that is not what that function does. That functions resets the iostate flags and that is not what you are looking for. If you want to clear the buffer then you have to call std::cin::ignore
I am a beginner to C++ and pretty much programming altogether (besides a little html and css).
I have decided to start my first project for C++.
A friend recommended me trying to make a simple calculator so here is my first shot. Any pointers would be great too! Not sure exactly what I am missing, if anything, but the error I am receiving is:
1>------ Build started: Project: CalculatorFinal, Configuration: Debug Win32 ------
1> CalculatorFinal.cpp
1>c:\users\ramee\documents\visual studio 2010\projects\calculatorfinal
\calculatorfinal\calculatorfinal.cpp(32): warning C4102: 'calc' : unreferenced label
1> CalculatorFinal.vcxproj -> c:\users\ramee\documents\visual studio 2010
\Projects\CalculatorFinal\Debug\CalculatorFinal.exe
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========
my code is below (apologize if its not formatted correctly on here. This is my first post :D
// CalculatorFinal.cpp : Defines the entry point for the console application.
//
#include "stdafx.h" // Including header
#include <iostream> // Including ioStream
using namespace std; // Namespace
void calc (double x, double y);
double result;
double n1,n2; // Declaring Variables
char q,operation;
int main()
{
cout<<"Welcome to My Calculator" <<endl; // Outputs welcome message
cout<<""<<endl; // Blank Space
cout<<"INSTRUCTIONS: Input a mathmatical equation" <<endl; // Outputs instruction
cout<<" EX: 2 + 2" <<endl; // Outputs instruction
cout<<""<<endl; // Blank Space
cout<<"Operators:"<<endl; // Outputs operation header
cout<<"For Addition, select '+'"<<endl // Outputs ADD instruction
cout<<"For Subtraction, select '-'"<<endl; // Outputs SUB instruction
cout<<"For Multiplication, select '*'"<<endl; // Outputs MUL instruction
cout<<"For Division, select '/'"<<endl; // Outputs DIV instruction
cout<<""<<endl; // Blank Space
cout<<"To clear, select 'c'"<<endl; // Outputs clear instruction
cout<<"To quit, select 'q'"<<endl; // Outputs QUIT instruction
cout<<""<<endl; // Blank Space
cout<<"Input a mathmatical equation"<<endl; // Input instructions
cin>>n1>>operation>>n2;
calc:(n1,n2);
cout<<"The answer is:"<<result<<endl;
std::cin>>q; // Input "q" to "quit"
return 0;}
void calc(double x, double y) // Operator function
{ x=n1;
y=n2;
switch(operation) // Operator swtich statement
{case '+':
result = x + y;
break;
case '-':
result = x - y;
break;
case '*':
result = x * y;
break;
case '/':
result = x / y;
break;
default:
cout<<"Improper equation. Please input a valid mathmatical equation"<<endl;
cin>>n1>>operation>>n2;
calc (n1,n2);
}
}
Here is a calculator program I wrote based off of yours which is much nicer:
#include <iostream>
using namespace std;
//Function prototype
int solve(int, int, char);
int main()
{
//Declare variables
int solution, num1, num2;
char oper;
//Output
cout << "Calculator\n----------\n" << endl;
cout << "Syntax:\n" << endl;
cout << "1 + 3\n" << endl;
cout << "Operators: +, -, *, /\n" << endl;
cout << "Equation: ";
//Input
cin >> num1 >> oper >> num2;
//Solve and output
solution = solve(num1, num2, oper);
cout << "Answer: " << solution << endl;
//Pause [until enter key] and exit
cin.ignore(); //Enter key from last cin may be passed, ignore it.
cin.get();
return 0;
}
int solve(int num1, int num2, char oper)
{
//Switch oper
switch(oper)
{
case '+':
return num1 + num2;
case '-':
return num1 - num2;
case '*':
return num1 * num2;
case '/':
return num1 / num2;
default:
cout << "\nIncorrect operation! Try again: ";
cin >> num1 >> oper >> num2;
solve(num1, num2, oper);
}
}
Here are some things to watch out for, from your last program:
1) Function prototypes do not have function names [i.e void func(int)]
2) Use return values [i.e. return result;]
3) Make sure you have semi-colons.
.
.
.
.
[OLD POST:
cout<<"For Addition, select '+'"<;* // Outputs ADD instruction
[No ending semi-colon]
FYI:
std::cin>>q; // Input "q" to "quit"
std:: not required here. (using namespace std;)
(remove colon in calc:(n1,n2);)
--
Your program will work now.]
I wouldn't call this as a C++ program. It is a mistake which almost all amateur C++ programmers make. I would call this as a C style of writing C++ programs. Please don't get me wrong but you need to start thinking in object oriented way so that you can leverage the true power of C++.
I would recommend you to make a C++ class called calculator and think on the design of the class for a bit before starting to code. I would keep methods such as Add, Subtract, Divide and so on as public and other methods as private. This would also give you a chance to enhance the calculator class in future like say adding memory support to it so that it remembers the last operation or result. Start thinking in object oriented way, in order to avoid spaghetti code which is difficult to manage later.
I've commented that I have changed from your original source code.
and I've checked this code is working on GCC ( G++ ) compiler
Good luck!
#include "stdafx.h"
#include <iostream>
using namespace std;
void calc (double _x, double _y); // CHANGED
double result;
double n1,n2;
double x,y; // CHANGED
char q,operation;
int main()
{
cout<<"Welcome to My Calculator" <<endl;
cout<<""<<endl;
cout<<"INSTRUCTIONS: Input a mathmatical equation" <<endl;
cout<<" EX: 2 + 2" <<endl;
cout<<""<<endl;
cout<<"Operators:"<<endl;
cout<<"For Addition, select '+'"<<endl;
cout<<"For Subtraction, select '-'"<<endl;
cout<<"For Multiplication, select '*'"<<endl;
cout<<"For Division, select '/'"<<endl;
cout<<""<<endl;
cout<<"To clear, select 'c'"<<endl;
cout<<"To quit, select 'q'"<<endl;
cout<<""<<endl;
cout<<"Input a mathmatical equation"<<endl;
cin>>n1>>operation>>n2;
calc(n1,n2); // CHANGED
cout<<"The answer is:"<<result<<endl;
std::cin>>q;
return 0;
}
void calc(double _x, double _y) // CHANGED
{
x=_x; // CHANGED
y=_y; // CHANGED
switch(operation)
{case '+':
result = x + y;
break;
case '-':
result = x - y;
break;
case '*':
result = x * y;
break;
case '/':
result = x / y;
break;
default:
cout<<"Improper equation. Please input a valid mathmatical equation"<<endl;
cin>>x>>operation>>y; // CHANGED
calc (x,y); // CHANGED
}
}
This is my code,it too long but support more operators
#include "stdafx.h"
#include"iostream"
#include"math.h"
#include"iomanip"
#include <string>
#include <sstream>
using namespace std;
double calc(string mystring);
double calc2(string mystring);
double factoriel(double number);
double root(double num1,double num2);
double dowork(int a,int b,string c);
int main(){
cout<<"***************************************************\n";
cout<<"* *\n";
cout<<"* calculator *\n";
cout<<"***************************************************\n\n\n";
string inpstring;
cin >> inpstring;
int length_string=inpstring.length();
double result;
if(abs(calc(inpstring))>abs(calc2(inpstring))){
result=calc(inpstring);
}
else if(abs(calc(inpstring))<=abs(calc2(inpstring))){
result=calc2(inpstring);
}
double s;
s=3.14;
cout<<"\n"<<"\tresult : "<<result<<endl;
system("pause");
}
double calc(string mystring){
int a=0;//just for switchings
int numberofop=0;
int length_string=mystring.length();
string ops;
string myop;
double param1=0;
double param2=0;
double result=0;
string first_inp;
string second_inp;
ops="+-*/^%!R";
int length_ops=ops.length();
for (int i=0;i<=length_string-1;i++){
if (i==0){
if(mystring.substr (0,1)=="-"){
continue;
}
}
for (int j=0;j<=length_ops-1;j++){
if (!(mystring.substr (i,1).compare(ops.substr(j,1)))){
numberofop++;
if (numberofop==1){
myop=ops.substr(j,1);
first_inp = mystring.substr (0,i);
second_inp = mystring.substr (i+1,length_string-1);
stringstream(first_inp) >> param1;
stringstream(second_inp) >> param2;
if (myop=="+"){
a=1;
}
else if(myop=="-"){
a=2;
}
else if(myop=="*"){
a=3;
}
else if(myop=="/"){
a=4;
}
else if(myop=="^"){
a=5;
}
else if(myop=="%"){
a=6;
}
else if(myop=="!"){
a=7;
}
else if(myop=="R"){
a=8;
}
}
}
}
}
switch (a){
case 1:
result=param1+param2;
break;
case 2:
result=param1-param2;
break;
case 3:
result=param1*param2;
break;
case 4:
result=param1/param2;
break;
case 5:
result= pow(param1,param2);
break;
case 6:
result= int(param1)% int(param2);
break;
case 7:
result= factoriel(param1);
break;
case 8:
result= root(param1,param2);
break;
}
return result;
}
double factoriel(double a){
cout<<"enter number \n";
double i=a;
double d=1;
while(i>1){
d=d*i;
i--;
}
return d;
}
double root(double num1,double num2){
double result;
double reverce;
reverce=1/num2;
result=pow(num1,reverce);
return result;
}
double calc2(string mystring){
int a=0;//just for switchings
int numberofop=0;
int length_string=mystring.length();
double pi=3.1415;
double teta;
string ops;
string myop;
double param1=0;
double param2=0;
double result=0;
string first_inp;
string second_inp;
ops="logsincostancot";
int length_ops=ops.length();
for (int i=0;i<=length_string-1;i++){
if (i==0){
if(mystring.substr (0,1)=="-"){
continue;
}
}
for (int j=0;j<=length_ops-1;j++){
if (!(mystring.substr (i,3).compare(ops.substr(j,3)))){
numberofop++;
if (numberofop==1){
myop=ops.substr(j,3);
second_inp = mystring.substr (i+3,length_string-1);
stringstream(second_inp) >> param2;
if (myop=="log"){
a=1;
}
else if(myop=="sin"){
a=2;
}
else if(myop=="cos"){
a=3;
}
else if(myop=="tan"){
a=4;
}
else if(myop=="cot"){
a=5;
}
}
}
}
}
switch (a){
case 1:
result=log(param2);
break;
case 2:
teta=(double(param2)*pi)/180;
result=sin(teta);
break;
case 3:
teta=(double(param2)*pi)/180;
result=cos(teta);
break;
case 4:
teta=(double(param2)*pi)/180;
result=tanf(teta);
break;
case 5:
teta=(double(param2)*pi)/180;
result=1/tanf(teta);
break;
}
return result;
}
double dowork(int a,int b,string c){
string cut;
cut=c.substr(a,b);
double result;
result=calc(cut);
cout<<"\nresult is "<<result;
return result;
}
I had coded this simple calculator using c++ so that we can add, subtract, divide or multiple as many numbers as we want. example: 2+3+4-2= and then you will get your answer.
#include <iostream>
#include <conio.h>
using namespace std;
int main()
{
char c;
while(true){
cout << "To solve your math problem you can use this syntex: number(+, -, / or *)number=" << endl;
cout << "you can use as many number as you want." << endl << endl;
int n, ans;
char oper;
cin >> n;
ans = n;
cin >> oper;
while(oper!='='){
cin >> n;
if(oper=='+'){
ans = ans + n;
}
if(oper=='-'){
ans = ans - n;
}
if(oper=='/'){
ans = ans/n;
}
if(oper=='*'){
ans = ans*n;
}
cin >> oper;
}
cout << "answer: " << ans << endl << endl;
cout << "Press esc to exit or press any key to continue." << endl << endl;
c=getch();
if(c==27){
break;
}
}
return 0;
}
Here's my take at it, without making a class. Completely new from yours.
#include <iostream>
#include <cstdlib>
using namespace std;
double a, b;
char operation;
int main()
{
cout << "Welcome to my calculator program.\n";
cout << "To make a calculation simply use the following operators -> (+ - * /).\n";
cout << "To exit, simply write an operation but replace the operator with 'q'. (eg. 2q3).\n";
while (operation != 'q'){
cin >> a >> operation >> b;
if(std::cin.fail()){
cout << "Input not numerical. Exiting...";
exit(1);
}
switch (operation)
{
case '+':
cout << " = " << a + b << '\n';
break;
case '-':
cout << " = " << a - b << '\n';
break;
case '*':
cout << " = " << a * b << '\n';
break;
case ':':
case '/':
cout << " = " << a / b << '\n';
}
}
return 0;
}