C++ Newbie questions - c++

My task:
Write the following program: The user is asked to enter 2 floating point numbers (use doubles). The user is then asked to enter one of the following mathematical symbols: +, -, *, or /. The program computes the answer on the two numbers the user entered and prints the results. If the user enters an invalid symbol, the program should print nothing.
My code:
#include <iostream>
using namespace std;
int introducir()
{
int a;
cin >> a;
return a;
}
bool simbolo(char x)
{
if (x == '+')
return true;
if (x == '-')
return true;
if (x == '*')
return true;
if (x == '/')
return true;
return false;
}
void operar(char x, int a, int b)
{
if (x == '+')
cout << a+b;
if (x == '-')
cout << a-b;
if (x == '*')
cout << a*b;
if (x == '/')
cout << a/b;
else cout << "INVALID OPERATION SIMBOL";
}
int main()
{
cout << "insert 2 numbers"<< endl;
int a =introducir();
int b= introducir();
cout << "introduce one of these simbols : +,-,* o /." << endl;
char x;
cin >> x;
bool primo= simbolo(x);
{
if (primo) {
cout << "simbol is valid" << endl;
} else {
cout << "invalid simbol" << endl;
}
cout << "operation result is:";
}
operar(x,a,b);
}
If the symbol is not in (+,-,*,/), I want it to return a message "INVALID OPERATION SIMBOL"; however it returns it even if the symbols are valid. How do I fix that?

The way you've written it, the else only applies to the final if.
Change to
if (x == '+'){
cout << a+b;
} else if (x == '-'){
cout << a-b;
} else if (x == '*'){
cout << a*b;
} else if (x == '/'){
cout << a/b;
} else {
cout << "INVALID OPERATION SIMBOL";
}
and similar for the other if statements. (You could even consider refactoring to a switch block.) The braces are not entirely necessary but I've put them in for clarity.

Related

calling function on while loop

I'm making a calculator program but I already encounter a problem. Well, my code is in a loop that will call a function to display the choices and then ask the user to pick, a/s/m/d are the choices. If the input is on the choices, it will proceed to the next step. Otherwise, it will loop and then call the function again.
#include <iostream>
using namespace std;
void home()
{
cout << "\nChoose your operation:" << endl;
cout << "\tType [A] for Addition" << endl;
cout << "\tType [S] for Subtraction"<< endl;
cout << "\tType [M] for Multiplication" << endl;
cout << "\tType [D] for Division" << endl;
}
int main()
{
char operation;
bool no_operator = true;
int design = 73;
for (int i = 0; i < design; i++){
if (i == 25){
cout << " WELCOME TO CALCULATOR ";
i += 22;
}
else i == 72 ? cout << "*\n" : cout << "*";
}
while (no_operator){
home();
cout << "\nOperation: ";
cin >> operation;
if (operation == 'A' || operation == 'a')
{
cout << "\nIt will going to add numbers";
no_operator = false;
}
else if (operation == 'S' || operation == 's')
{
no_operator = false;
cout << "\nIt will going to subtract numbers";
}
else if (operation == 'M' || operation == 'm')
{
no_operator = false;
cout << "\nIt will going to multiply numbers";
}
else if (operation == 'D' || operation == 'd')
{
no_operator = false;
cout << "\nIt will going to divide numbers";
}
else
{
cout << "\tInvalid Input: You must enter A/S/M/D only\n";
//home();
}
}
return 0;
}
My problem is it will run the '''home()''' in else statement even if the input is correct on the second loop.
I want to stop the '''home()''' to be called when the input is correct
Your code works perfectly fine. Make sure you're inputting the correct letters.
Also for this code, a "do while()" loop would be better.
You program is working perfectly fine as the input is correct it does not show the home rather print the message it will going to divide etc.

C++ Basic Calculator

I'm new to C++ and programming in General. I was assigned to make a calculator for my C++ class and this is what I have so far.
#include <iostream>;
#include <iomanip>;
using namespace std;
int main() {
double x,y;
char op;
cout << "Enter Expression:";
cin >> x >> op >> y;
if (op = '+')
{
cout << "Result:" << x + y << endl;
}
else if (op = '-') {
cout << "Result:" << x - y << endl;
}
else if (op = '*') {
cout << "Result:" << x*y << endl;
}
else if (op = '/') {
cout << "Result:" << x / y << endl;
}
else if (op = '%') {
cout << "Result:" << x % y << endl; // <--- line 23
}
else {
return 0;
}
}
The x and y variables on line 23 both have errors saying that the expression must have an integral or unscoped enum type and I don't understand why.
The % operation is defined only for integer values. You cannot apply it for doubles. Also you have a typical novice mistake: In C++ operator = is assignment operator a = b mean get b value and put it in a. But operator == is comparison operator, a == b mean if a equally b return true. If you want to compare values use ==, not =.
With floating point division there is no remainder. What should be the result of 2.5 % 1.2?
You could use ints for that case:
else if (op == '%') {
cout << "Result:" << (int)x % (int)y << endl;
}
but note that when the user types 2.5 % 1.2 this will show the result for 2 % 1.
PS: Also note that you have = (assignment) in the conditions when it should be == (comparison).
You are using % for double, it is only for integers.
If you want to use same functionality for double. you can use fmod()
double z = fmod(x,y);
You should modify your code to below
#include <iostream>;
#include <iomanip>;
using namespace std;
int main() {
double x,y;
char op;
cout << "Enter Expression:";
cin >> x >> op >> y;
if (op == '+')
{
cout << "Result:" << x + y << endl;
}
else if (op == '-') {
cout << "Result:" << x - y << endl;
}
else if (op == '*') {
cout << "Result:" << x*y << endl;
}
else if (op == '/') {
cout << "Result:" << x / y << endl;
}
else if (op == '%') {
cout << "Result:" << fmode(x,y) << endl;
}
else{
return 0;
}
}
The remainder operator % does not work for operands of type double (cf., for example, cppreference.com/Multiplicative operators):
For the built-in operator %, lhs and rhs must both have integral or
unscoped enumeration type
You could write static_cast<int>(x)%static_cast<int>(y) instead.
Further, note that = is assignment operator; for comparisons (as in your case with if (op = '%')), use equality operator ==, i.e. if (op == '%').

Having trouble with a 'while' loop in C++

I started building a very simple version of a calculator in C++. The idea is to perform basic operations with only two numbers and then loop back so the user can make a new calculation.
The program looks like this:
#include<iostream>
#include<string>
#include"mathOperations.h"
using namespace std;
int main()
{
int x, y;
string operation;
string repeat = "y";
while (repeat == "y" or "Y")
{
cout << "Welcome! This is a raw version of a calculator - only use two numbers." << endl;
cin >> x >> operation >> y;
if (operation == "+")
{
cout << "Result: " << add(x, y) << endl;
}
else if (operation == "-")
{
cout << "Result: " << subtract(x, y) << endl;
}
else if (operation == "*")
{
cout << "Result: " << multiply(x, y) << endl;
}
else if (operation == "/")
{
cout << "Result: " << divide(x, y) << endl;
}
else
{
cout << "This is not a valid sign. Please choose another one!" << endl;
}
cout << "Wanna go again? Type 'y' or 'n'." << endl;
cin >> repeat;
if (repeat == "n" or "N")
{
cout << "Alright, have a nice day!" << endl;
break;
}
}
}
int add(int x, int y)
{
return x + y;
}
int subtract(int x, int y)
{
return x - y;
}
int multiply(int x, int y)
{
return x * y;
}
int divide(int x, int y)
{
return x / y;
}
NOTE: There is a 'mathOperations.h' file in which I have made forward declarations of all functions used.
The problem is that whenever I type in 'y' to make it loop, it simply outputs the following 'if' statement and breaks out of the loop and the program finishes. I couldn't quite figure out why this is happening, since the 'if' statement is only supposed to run if I type in 'n'.
repeat == "n" or "N"
evaluates to
(repeat == "n") || "N"
see the C++ operator precedence.
The first repeat == "n" evaluates to true or false depending on your input, but the second clause of the OR, i.e. "N", always evaluates to true because it is a string literal that decays to a non-zero const char* pointer, and in C or C++ everything non-zero is implicitly converted to true. So your OR clause is always true, which implies that the if block will always be executed.
As mentioned in the comments, you need to do
if(repeat == "n" || repeat == "N") {...}
Similarly with the first while condition.
Nice code! I try using "||" in place of your "or" in your if statements. Might want to refresh your knowledge with C++ short-circuiting of booleans.

C++ calling different methods if char is entered

Hello I'm trying to create a console application that allows the user to input a single character to preform an arithmetic operation.
Currently the program only adds the two numbers together even if I input an m, meaning multiply. I believe it is going straight into the first if statement for some reason even if I dont want addition.
#include <iostream>
using namespace std;
int add(int a, int b)
{
int c;
c = a + b;
return c;
}
int subtract(int a, int b)
{
int c;
c = a - b;
return c;
}
int multiply(int a, int b)
{
int c;
c = a * b;
return c;
}
int divide(int a, int b)
{
int c;
c = a / b;
return c;
}
int remainder(int a, int b)
{
int c;
c = a % b;
return c;
}
int main ()
{
int a;
int b;
char op;
cout << "****************Integer Calculator**************** " << endl << "Press enter to continue." << endl;
cout << "Enter the first integer: " << endl;
cin >> a;
cout << "Enter the second integer: " << endl;
cin >> b;
cout << "What operation would you like to perform? Enter a single character " << endl << "Add - A , a or + " << endl <<
"Subtract - S , s or - " << endl << "Multiply - M , m or * " << endl << "Divide - D , d or / " << endl << "Remainder - R , r or % " << endl;
cin >> op;
if (op ='A' || 'a' || '+')
{
int answer1 = 0;
answer1 = add(a, b);
cout << "The answer is: " << answer1 << endl;
system("PAUSE");
return 0;
}
else if(op == 'S' || 's' || '-')
{
int answer2 = 0;
answer2 = subtract(a, b);
cout << "The answer is: " << answer2 << endl;
system("PAUSE");
return 0;
}
else if (op == 'M' || 'm' || '*')
{
int answer3 = 0;
answer3 = multiply(a, b);
cout << "The answer is: " << answer3 << endl;
system("PAUSE");
return 0;
}
else if (op == 'D' || 'd' || '/')
{
int answer4 = 0;
answer4 = divide(a, b);
cout << "The answer is: " << answer4 << endl;
system("PAUSE");
return 0;
}
else if (op == 'R' || 'r' || '%')
{
int answer5 = 0;
answer5 = remainder(a, b);
cout << "The answer is: " << answer5 << endl;
system("PAUSE");
return 0;
}
Your logic is incorrect, and you are using the assignment operator to boot.
if (op ='A' || 'a' || '+')
This should be:
if (op == 'A' || op == 'a' || op == '+')
Usually for stuff like this we use a switch:
switch( toupper(op) )
{
case 'A':
case '+':
// Do adding...
break;
case 'S':
case '-':
// Do subtraction...
break;
// etc...
default:
cout << "Unknown operation : " << op << endl;
}
In your if statement
(op ='A' || 'a' || '+')
you are not testing if op equals 'A'. You are setting op equal to 'A', and then testing if 'a' and '+' are true, which they are. To fix this, use the == operator, and test op for every case like so:
if (op == 'A' || op == 'a' || op == '+')...
else if(op == 'S' || op == 's' || op == '-')...
// and so on

C++ Mathematical Expression Parser Issue

#include <iostream>
#include <string>
#include <queue>
#include <stack>
#include "NodeType.h"
using namespace std;
// Test if token is an operator
bool isOperator(char token);
int getPrecedence(char token);
bool comparePrecedence(char tokenA, char tokenB);
int main()
{
stack<char> tokenStack;
queue<char> tokenQueue;
string expression= "", postfix= "";
char x;
cout<<"Please enter a mathematical expression: "<<endl;
getline(cin, expression);
cout<<expression.length()<<endl;
for(int i = 0; i <= expression.length(); i++)
{
x = expression[i];
if(isdigit(x))
{
tokenQueue.push(x);
}
if(isOperator(x))
{
while((!tokenStack.empty()) && (comparePrecedence(x, tokenStack.top() == true)))
{
char z = tokenStack.top();
tokenQueue.push(z);
tokenStack.pop();
}
tokenStack.push(x);
}
if(x == '(')
{
tokenStack.push(x);
}
if(x == ')')
{
while((!tokenStack.empty()) && (tokenStack.top() != '('))
{
char z = tokenStack.top();
tokenQueue.push(z);
tokenStack.pop();
}
tokenStack.pop();
}
while(!tokenStack.empty())
{
char z = tokenStack.top();
tokenQueue.push(z);
tokenStack.pop();
}
}
return 0;
}
int getPrecedence(char token)
{
if((token == '+') || (token == '-'))
{
return 1;
}
else if((token == '*') || (token == '/'))
{
return 2;
}
else if ((token == '(') || (token == ')'))
return 0;
else
return 99;
}
// Test if token is an operator
bool isOperator(char token)
{
return token == '+' || token == '-' ||
token == '*' || token == '/';
}
bool comparePrecedence(char tokenA, char tokenB)
{
if(getPrecedence(tokenA) < getPrecedence(tokenB))
return true;
else
return false;
}
For some reason I cannot get my code to work correctly. It always throws a
Thread 1: EXC_BAD_ACCESS (code=EXC_1386_GPFLT) error. It is also not correctly placing the '+' sign when I test using a simple string such as: (3+4).
The Queue should look like: 34+ but it hold 3+4. It seems to me that the '+' operator never gets pushed onto the stack. Can anyone please help me find what I should be focussing my attention on?
Debugging code is a valuable skill to learn, it's my opinion that it should form a much more important part of curricula in schools.
For example, if you modify your code to output all the stack and queue operations thus:
int main()
{
stack<char> tokenStack;
queue<char> tokenQueue;
string expression= "", postfix= "";
char x;
cout<<"Please enter a mathematical expression: "<<endl;
getline(cin, expression);
cout<<expression.length()<<endl;
for(int i = 0; i <= expression.length(); i++)
{
x = expression[i];
if(isdigit(x))
{
tokenQueue.push(x);
cout << "qpush A " << x << '\n';
}
if(isOperator(x))
{
while((!tokenStack.empty()) && (comparePrecedence(x, tokenStack.top() == true)))
{
char z = tokenStack.top();
tokenQueue.push(z);
cout << "spop G " << z << '\n';
cout << "qpush B " << z << '\n';
tokenStack.pop();
}
tokenStack.push(x);
cout << "spush E " << x << '\n';
}
if(x == '(')
{
tokenStack.push(x);
cout << "spush F " << x << '\n';
}
if(x == ')')
{
while((!tokenStack.empty()) && (tokenStack.top() != '('))
{
char z = tokenStack.top();
tokenQueue.push(z);
cout << "spop H " << z << '\n';
cout << "qpush C " << z << '\n';
tokenStack.pop();
}
cout << "spop I " << tokenStack.top() << '\n';
tokenStack.pop();
}
while(!tokenStack.empty())
{
char z = tokenStack.top();
tokenQueue.push(z);
cout << "spop J " << z << '\n';
cout << "qpush D " << z << '\n';
tokenStack.pop();
}
}
return 0;
}
and run it with a simple 3+4, you'll see the following output:
qpush A 3
spush E +
spop J +
qpush D +
qpush A 4
So you are placing the operation on the stack. However, you later take it off the stack and put it on the queue before you place the next digit on the queue.
That's definitely the wrong order but, if you examine the code, it's not just a small snippet that has two lines in the wrong order (that would be too easy).
The code that's doing that transfer from stack to queue is the final while loop in main() which, after every single character, transfers all the items from the stack to the queue, effectively rendering your stack superfluous.
That's where you should be looking but I'll give you a clue. You don't want to be transferring stack to queue after every character, only for those that involve numbers.
There may well be other problems after you solve that one but that method (debugging output every time you do something important) should be able to give you enough information to fix whatever comes along.