C++ calling different methods if char is entered - c++

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

Related

This currency coverter in c++ doesn't work

problem: the cout is always strange numbers or the else cout or the cout that say "useless conversion"
. I've tried also using integers and strings instead of letters for the currencies but doesn't work anyway
I've done in Object oriented programming for necessity
#include<iostream>
using namespace std;
/*Object oriented programming*/
class Convertitore{
public:
char vEntrata, vUscita;
double qEntrata;
Convertitore();
Convertitore(char vEntrata, char vUscita, double qEntrata);
double Calcolo();
};
Convertitore::Convertitore(){
vEntrata = 'a';
vUscita = 'a';
qEntrata = 0;
}
Convertitore::Convertitore(char vEntrata, char vUscita, double qEntrata){
vEntrata = vEntrata;
vUscita = vUscita;
qEntrata = qEntrata;
}
double Convertitore::Calcolo(){
if(vEntrata == 'e' && vUscita == 'e'){
cout << "Useless conversion";
}
else if(vEntrata == 'e' && vUscita == 'd'){
cout << qEntrata << "€ equal to " << qEntrata*1.22 << "$";
}
else if(vEntrata == 'e' && vUscita == 'l'){
cout << qEntrata << "€ equal to " << qEntrata*1936 << "£";
}
else if(vEntrata == 'd' && vUscita == 'e'){
cout << qEntrata << "$ equal to " << qEntrata/1.22 << "€";
}
else if(vEntrata == 'd' && vUscita == 'd'){
cout << "Useless conversion";
}
else if(vEntrata == 'd' && vUscita == 'l'){
cout << qEntrata << "$ equal to " << qEntrata*1510.29 << "£";
}
else if(vEntrata == 'l' && vUscita == 'e'){
cout << qEntrata << "£ equal to " << qEntrata/1936.27 << "€";
}
else if(vEntrata == 'l' && vUscita == 'd'){
cout << qEntrata << "£ equal to " << qEntrata/1510.29 << "$";
}
else if(vEntrata == 'l' && vUscita == 'l'){
cout << "Useless conversion";
}
else{
cout << "wrong inputs";
}
}
int main(){
char vEntrata, vUscita;
double qEntrata;
cout << "Scegli la valuta da convertire: digita e per euro, d per dollar, l per italian lira: "; cin >>
vEntrata;
cout << "Scegli la valuta in cui convertire: digita e per euro, d per dollar, l per italian lira: "; cin
>> vUscita;
cout << "digitare la quantità di " << vEntrata << " da convertire: "; cin >> qEntrata;
Convertitore Valuta = Convertitore(vEntrata, vUscita, qEntrata);
cout << Valuta.Calcolo();
return 0;
}
In your constructor
Convertitore::Convertitore(char vEntrata, char vUscita, double qEntrata){
vEntrata = vEntrata;
vUscita = vUscita;
qEntrata = qEntrata;
}
You are assigning local variables to themselves.
You can use the member initializer list instead:
Convertitore::Convertitore(char vEntrata, char vUscita, double qEntrata)
: vEntrata(vEntrata),
vUscita(vUscita),
qEntrata(qEntrata)
{}
Secondly your function double Convertitore::Calcolo() promises to return a double, but doesn't return anything.
Because of this the line
cout << Valuta.Calcolo();
causes undefined behaviour and most likely will print garbage data.
It seems like Calcolo isn't designed to return something, but print the result directly. If that's what you want, change the return type to void:
void Convertitore::Calcolo()
and don't attempt to print the (now non-existent) return value.

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 == '%').

C++ Newbie questions

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.

Storing multiple user input into an array

I am currently working on a program for a project, that asks for the user to enter the specific sport they want to play and their age for reservations at a recreation area. I am confused on how to store their sport and age into an array so that it can be displayed later in the program, if they select to view all reservations made by one or more users. If anyone could help me with figuring out how to store a single or multiple user input into an array so that it can be displayed later in the program that would be great!
#include <iostream>
#include <string>
using namespace std;
int main()
{
char t; // Type of sport selected
char g, G; // Gliding
char h, H; // Hang-gliding
char f, F; //Flying
int a; // Age of patron
double x; // Rates
int s; // Selection from menu
int i; // Arrays variable
int num;
char sport[100]; // Array for all sports of patrons
int age[100]; // Array for all ages of patrons
cout << "Please pick from the following menu" << endl;
cout << "1. Add a new reservation" << endl;
cout << "2. Print all reservations" << endl;
cout << "3. Print all reservations for a given sport" << endl;
cout << "4. Quit" << endl;
cin >> s;
for (i = 0; i < num; ++i)
if (s == 1) {
cout << "Please enter f/F for flying, g/G for gliding and h/H for hang-gliding" << endl;
cin >> t;
getline (cin, sport[i]);
cout << "Please enter the age of patron, minimum age is 16" << endl;
cin >> a;
if ((t == 'f' || t == 'F') && (a <= 25)) {
x = 68.95;
}
else if ((t == 'g' || t == 'G') && (a <= 25)) {
x = 73.95;
}
else if ((t == 'h' || t == 'H') && (a <= 25)) {
x = 99.95;
}
else if ((t == 'f' || t == 'F') && (a > 25)) {
x = 55.95;
}
else if ((t == 'g' || t == 'G') && (a > 25)) {
x = 65.95;
}
else if ((t == 'h' || t == 'H') && (a > 25)) {
x = 92.95;
}
cout << "The insurance rate is $ " << x << endl;
}
else if (s == 2) {
cout << "A patron aged " << a << " reserved a session of " << t << endl;
}
else if (s == 3) {
}
else if (s == 4);
return 0;
You should make a class Patron that contains the multiple informations, then make an array of type Patron instead of multiple arrays:
class Patron
{
//data for each patron...
};
in main:
Patron patrons[...];
You could also use dynamic containers, like vector instead of an array.
std::vector<Patron> patrons;

Why won't this C++ While loop work? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm simply trying to get the user to put in their name/age and verify if it's correct. If not then they get 4 tries before the program will abort. However my while loops don't loop, instead they just continue on to the next loop. I've tried a variation of things inside the while parenthesis (op != 1) (!(op = 1)) etc.
int main() {
system("Color 0A");
string name;
int age;
int tries = 0;
int op = 0;
cout << "Hello User" << endl;
Sleep(3000);
while ((op != 1) && (tries < 4)) {
name = entName(name);
cout << "So your name is " << name << "?" << endl;
cout << "Enter '1' for YES or '2' for NO. ";
cin >> op;
if (op == 1) {
cout << "Perfect!";
}
if (op == 2) {
cout << "Please Try Again!";
tries+ 1;
}
if (tries = 4) {
//abort the program
}
}
int op2 = 0;
int tries2 = 0;
while ((op2 != 1) && (tries2 < 4)) {
op2 = 3;
age = entAge();
cout << "So you are " << age << " years old?" << endl;
while ((op2 != 1) && (op2 != 2)) {
cout << "Enter '1' for YES or '2' for NO. ";
cin >> op2;
if (op2 == 1) {
cout << "Perfect!\n";
}
if (op2 == 2) {
cout << "Please Try Again!\n";
tries2++;
}
if (tries2 = 4) {
//abort the programhi
}
}
}
return 0;
}
I'm fairly new to C++ so I'm sorry if it does have a simple answer. But anyway, I've been debugging this for over half an hour and I looked online for 20+ minutes.
if (tries = 4) {
//abort the program
}
Change this to
if (tries == 4) {
//abort the program
}
And
f (op == 2) {
cout << "Please Try Again!";
tries+= 1; // tries+ 1;
}
You can increment value in C++ like this tries+ 1;. Either use tries+= 1; or tries++;
tries+ 1; should be tries += 1; or tries++;
And,
if (tries = 4) {
//abort the program
}
should be:
if (tries == 4) {
//abort the program
}
Your program should look like this:
int main()
{
system("Color 0A");
string name;
int age;
int tries = 0;
int op = 0;
cout << "Hello User" << endl;
Sleep(3000);
while ((op != 1) && (tries < 4)) {
name = entName(name);
cout << "So your name is " << name << "?" << endl;
cout << "Enter '1' for YES or '2' for NO. ";
cin >> op;
if (op == 1) {
cout << "Perfect!";
}
if (op == 2) {
cout << "Please Try Again!";
tries+= 1;
}
if (tries == 4) {
//abort the program
}
}
int op2 = 0;
int tries2 = 0;
while ((op2 != 1) && (tries2 < 4)) {
op2 = 3;
age = entAge();
cout << "So you are " << age << " years old?" << endl;
while ((op2 != 1) && (op2 != 2)) {
cout << "Enter '1' for YES or '2' for NO. ";
cin >> op2;
if (op2 == 1) {
cout << "Perfect!\n";
}
if (op2 == 2) {
cout << "Please Try Again!\n";
tries2++;
}
if (tries2 == 4) {
//abort the programhi
}
}
}
You have forget to use = sign at multiple places. tries = 4 should be tries == 4 for comparing variable tries with numeric 4. tries = 4 was reassigning the variable tries to four and your while loop was getting terminated after it's first run. Also, tries + 1 should be tries += 1 or tries++ to increment the value of tries variable by one.