How to seperate numbers in a string - c++

#include<iostream>
#include<cmath>
#include<string>
#include<fstream>
using namespace std;
struct Calculations //structure to hold the numbers and operators from 'equation'
{
double num1;
char operators;
double num2;
double answer;
};
Calculations myCalculationArray[SIZE]; // the array of calculations
int main()
{
while (i = 0; i <= 5; i++;)
{
cout << "Enter equation: \n";
getline(cin, equation);
cout << equation;
}
}
Alright so I'm trying to build a calculator where the user inputs an equation like "22/2", then to have it like assign the first number to num1 = ' 22 ' and the operator =' / ' to operators etc.

Since it seems like it is an homework for a student I will give you another solution for a calculator and you can modify it as you like ;)
#include<iostream>
#include<cmath>
using namespace std;
int main() {
char op;
float num1, num2;
cout << "Enter two operands: ";
cin >> num1 >> op >> num2;
switch(op)
{
case '+':
cout << num1+num2;
break;
case '-':
cout << num1-num2;
break;
case '*':
cout << num1*num2;
break;
case '/':
cout << num1/num2;
break;
default:
// If the operator is other than +, -, * or /, error message is shown
cout << "Error! operator is not correct";
break;
} }

You can take the help of strtok, strchr for parsing the string (separating out the operation symbol and the two numeric operands).
To convert the numeric string such as "34" to 34 , you can use the functions like atoi and atod etc.

Related

How to make a calculator in c++ using if else and functions?

I am a new contributor and here I am trying to make a simple calculator but having errors in my code. When I compile the code I get:
Error: C:\Users\IJLAL\Documents\collect2.exe [Error] ld returned 1 exit status while compiling
In case it could help, here is the screen shot of error when I pressed compile button or F11 in Dev C++:
Here is my code:
#include<iostream>
using namespace std;
void fun(float a, float b);
int main()
{
float a, b, sum, sub, mul, divide, mod;
char op;
//operands and operators are enterd by the user
cout<<"Enter any two operands with operator=";
cin>>a>>op>>b;
fun(a, b);
return 0;
}
void op(float a, float b)
{
if(a+b)
{
float sum=a+b;
cout<<"\nAddition of two numbers is="<<sum;
}
else if(a-b)
{
float sub=a-b;
cout<<"\nSubtraction of two numbers is="<<sub;
}
else if(a*b)
{
float mul=a*b;
cout<<"\nMultiplication of two numbers is="<<mul;
}
else if(a/b)
{
float divide=a/b;
cout<<"\nDivision of two number is="<<divide;
}
else
{
cout<<"\nInvalid operator.......";
}
}
Please tell me the solution of this problem, so that I can compile the code successfully. If there is any better solution to make a simple calculator on beginner level please mention it in answer.
You're not so far from a result. The problem is that you have not defined the function fun(). Furthermore, in the function op() that you have defined, you do not use the operator of the input.
So first thing to do is to change the signature of the function:
void fun(char op, float a, float b);
Then you need to invoke your function in main(), passing also the operation that was requested by the user:
fun(op, a, b);
Finally you need to change all your if to check if op is the matching operator:
void fun(char op, float a, float b)
{
if(op=='+')
{
...
}
else if(op=='-')
{
...
You should then get the expected result.
Online demo
Aditional infos
if (a+b) just calculates the expression using the two values of the user, and if it's non zero, it's considered as true.
once you got this program to work, you can look for the switch statement
You can use additional functions to make a better calculator. You can use this code. Hope this code will be helpful for you.
The header <iomanip> is part of the Input/output library of the C++ Standard Library and <math.h> is used when we perform mathematical operations.
#include<iostream>
#include<conio.h>
#include<math.h>
#include<iomanip>
char op;
using namespace std;
void sum()
{
int sum = 0;
int n;
int numberitems;
cout << "Enter number of items: \n";
cin >> numberitems;
for(int i=0;i<numberitems;i++)
{
cout<< "Enter number "<<i<<":\n\n" ;
cin>>n;
sum+=n;
}
cout<<"sum is: "<< sum<<endl<<endl;
}
void diff()
{
int diff;
int n1,n2;
cout<<"enter two numbers to find their difference:\n\n";
cout<<"enter first number:";
cin>>n1;
cout<<"\nenter second number:";
cin>>n2;
diff=n1-n2;
cout<<"\ndifference is:"<<diff<<endl<<endl;
}
void pro()
{
int pro=1;
int n;
int numberitems;
cout<<"enter number of items:\n";
cin>>numberitems;
for(int i=0;i<=numberitems;i++)
{
cout<<"\nenter item "<<i<<":";
cin>>n;
pro*=n;
}
cout<<"product is:"<<pro<<endl<<endl;
}
void div()
{
int div;
int n1;
int n2;
cout<<"enter 2 numbers to find their quotient\n\n";
cout<<"enter numerator:";
cin>>n1;
cout<<"\nenter denominator:";
cin>>n2;
div=n1/n2;
cout<<"\nquotient is:"<<div<<endl<<endl;
}
void power()
{
long int p;
int res=1,n;
cout<<"enter number:";
cin>>n;
cout<<"\nenter power:";
cin>>p;
for(int i=1;i<=p;i++)
{
res=n*res;
}
cout<<n<<"\n power "<<p<<" is :"<<res<<endl;
}
void sq()
{
float s;
int n;
cout<<"enter number to find its square root:";
cin>>n;
s=sqrt(n);
cout<<"\nsquare root of "<<n<<" is :"<<s<<endl;
}
void fact()
{
long int f=1;
int c=1,n;
cout<<"enter number to find its factorial:";
cin>>n;
while(c<=n)
{
f=f*c;
c+=1;
}
cout<<"\nfactorial of "<<n<<" is :"<<f<<endl;
}
void expo()
{
long double res=1,p;
double e=2.718281828;
cout<<"enter power of exponential function:";
cin>>p;
for(int i=1;i<=p;i++)
{
res=e*res;
}
cout<<" e^ "<<p<<" is :"<<res<<endl;
}
int main()
{
system("cls");
do
{
system("pause");
system("cls");
cout<<"***which operation you want to perform***\n";
cout<<"press 0 for exit\n";
cout<<"press 1 for addition \n";
cout<<"press 2 for subtraction\n";
cout<<"press 3 for multiplication\n";
cout<<"press 4 for division\n";
cout<<"press 5 for power calculation\n";
cout<<"press 6 for square root \n";
cout<<"press 7 for factorial calculation\n";
cout<<"press 8 for exponential calculation\n";
cout<<"press option:";
cin>>op;
switch(op)
{
case '1':
sum();
break;
case '2':
diff();
break;
case '3':
pro();
break;
case '4':
div();
break;
case '5':
power();
break;
case '6':
sq();
break;
case '7':
fact();
break;
case '8':
expo();
break;
case '0':
exit(0);
default:
cout<<"invalid input" ;
system("cls");
}
}
while(op!='0');
getch();
}
Hey I'm still a newbie on c++ but hope this would help, I used while loop to loop the calculator but I don't have a good error handler for example when users try to input a letter instead of numbers.
#include <iostream>
#include <cmath>
using namespace std;
int result (int a, int b, char op);
int main()
{
char optr, choice;
int nr1, nr2;
while (true){
cout << "Enter first number: ";
cin >> nr1;
cout << "Enter an operator (+ - / * %) : ";
cin >> optr;
cout << "Enter second number: ";
cin >> nr2;
result (nr1, nr2, optr);
cout<<"Would you like to perform other calculation?(Y/N): ";
cin >> choice;
if (choice =='N'||choice =='n'){
break;
}
}
}
int result (int a, int b, char op)
{
int result;
if (op == '+'){
result = a + b;
cout << "Result to " << a << " + " << b << " = " << result << endl;
} else if (op == '-'){
result = a - b;
cout << "Result to " << a << " + " << b << " = " << result << endl;
} else if (op == '*'){
result = a * b;
cout << "Result to " << a << " * " << b << " = " << result << endl;
} else if (op == '/'){
result = a / b;
a / b;
cout << "Result to " << a << " / " << b << " = " << result << endl;
} else if (op == '%'){
result = a % b;
cout << "Remainder to " << a << " % " << b << " = " << result << endl;
} else {
cout <<"Error 404: " << a << op << b <<" Wrong input format. Program terminated." << endl;
// i still dont know how to properly use error handling
}
}
I won't criticize your solution as I have a better solution as you mentioned "please mention a better solution in answer"
Here's my solution with comments to make you understand what each statement does.
#include <iostream>
using namespace std;
// I am going to show How to Design a program
// We have to break down our progress a bit by bit
// and do the progress of one thing with function
// For calculator we have to take input from user keyboard twice,
// And an opperator from user
int userInput() // this requires to get input from user keyboard
{
cout << "Enter a number: ";
int no{};
cin >> no;
return no;
}
char userOpr() // Using type char to store the ASCI Opperator means requires char to store +,*,/,-
{
cout << "Enter opperator: ";
char opr{};
cin >> opr;
return opr;
}
int calculate(int input1, char opper, int input2)
{
if (opper == '+')
{
return input1 + input2;
}
else if (opper == '-')
{
return input1 - input2;
}
else if (opper == '*')
{
return input1 * input2;
}
else if (opper == '/')
{
return input1 / input2;
}
return 0;
}
int main()
{
// get the first no. from user
// getUserInput();
// get the math oppperator from the user
// getMathOpperator();
// get the second no. from the user
// getUserInput();
// calculate the values
// calculateResults();
// print out the results
// printResults();
cout << "Hello This is a simple calculator program Designed by Shankhui!\n\n";
while (true)
{
int input1{ userInput() };
int input2{ userInput() };
char opper{ userOpr() }; // Using type char to store the ASCI Opperator means requires char to store +,*,/,-
cout << input1 << " " << opper << " " << input2 << " = " << calculate(input1, opper, input2) << '\n' << '\n';
}
return 0;
}
Just copy this code and modify however you want to.
#include <iostream>
int main() {
int math_ques_1, math_ques_2;
std::cout << "What is the base of the question?" << std::endl;
std::cin >> math_ques_1;
std::cout << "What do you want to add to the base?" << std::endl;
std::cin >> math_ques_2;
std::cout << "The answer is " << math_ques_1 + math_ques_2 << "." << std::endl; }

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;
...

Prefix to Infix?

In my class one of our assignments is to convert a prefix equation to infix. After reading that section I still have no idea what I'm doing. The book had some code that will solve a prefix equation when given but I have no idea how it does it or how I would display the infix version. Any help would be appreciated in explaining how this code finds the solution and how I could have it display a infix version.
#include <iostream>
#include <string>
#include <stdlib.h>
#include <sstream>
using namespace std;
int prefixExpr(istream &exprStream);
int main() {
string input;
cout << "Enter prefix expressions to evaluate. \nPress enter after each expression, and press enter on a blank line to quit." << endl;
cout << "Enter a prefix expression to evaluate: ";
getline(cin, input);
while (input.size() != 0){
istringstream exprStream(input);
cout << prefixExpr(exprStream) << endl;
cout << "Enter a prefix expression to evaluate: ";
getline(cin, input);
}
return 0;
}
int prefixExpr(istream &exprStream) {
char ch = exprStream.peek();
while (isspace(ch)) {
ch = exprStream.get();
ch = exprStream.peek();
}
cout << ch << endl;
if (isdigit(ch)) {
int number;
exprStream >> number;
cout << number << endl;
return number;
}
else {
ch = exprStream.get();
int value1 = prefixExpr(exprStream);
int value2 = prefixExpr(exprStream);
switch (ch) {
case '+': return value1 + value2;
case '-': return value1 - value2;
case '*': return value1 * value2;
case '/': return value1 / value2;
default: cout << "Bad input expression";
exit(1);
}
}
}

First C++ program help (calculator)

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;
}

Why am i getting this error? binary '==' : no operator found which takes a left-hand operand of type 'std::string'

I don't know why I'm getting this compile error. I tried the usual way to define strings and i also tries std::string but neither worked. Also I think there might be a problem with how I'm trying to print the function.
#include "stdafx.h"
#include <iostream>
#include <cmath>
#include <string>
float userInput1() // Defines the inputs from the user
{
using namespace std;
cout << "Please enter first number" << endl;
float number1;
cin >> number1;
return number1;
}
float userInput2() // Defines the inputs from the user
{
using namespace std;
cout << "Please enter second number" << endl;
float number2;
cin >> number2;
return number2;
}
std::string getOperation()
{
using namespace std;
cout<<"Please enter the operator. + - * /" << endl;
std::string userOperator;
cin>>userOperator;
return userOperator;
}
float computeValue(float value1, float value2, std::string operation)
{
using namespace std;
if(operation == '+')
{
cout<< value1 + value2<< endl;
}else if(operation =='-')
{
cout<< value1 - value2<< endl;
}else if(operation =='*')
{
cout<< value1 * value2<< endl;
}else if(operation == '/')
{
cout<< value1 / value2<< endl;
}else
{
cout<< "Please enter: + - * /"<< endl;
}
return 0;
}
int main(){
using namespace std;
computeValue(userInput1(), userInput2(), getOperation());
return 0;
}
You're comparing std::string with a char value using the == operator. The standard library does not define an equality operator between those two types. The list of valid comparisons is here: http://www.cplusplus.com/reference/string/string/operators/
The simplest way is to convert the char values into char* by using " instead of ', like so:
if(operation == '+')
becomes
if(operation == "+")
The problem is that you're comparing the string object to a character in your computeValue function. There no overload of operator == in the std namespace which takes both a std::string and a char, hence the error.
You should be using char instead of a std::string if you only need a character as input.
char getOperation()
{
std::cout << "Please enter the operator. + - * /" << std::endl;
char userOperator;
std::cin >> userOperator;
return userOperator;
}
Your parameter should also take a char:
float computeValue(float value1, float value2, char operation)
// ^^^^