I just want to say that this is my first time trying to learn a programming language so excuse my indifference. I am trying to get used to object oriented programming. The problem is I can't figure out how to get what the user inputted without storing it in a public variable.
#include <iostream>
using namespace std;
class Aclass{
public:
void setx(int a){
x = a;
}
void sety(int b){
y = b;
}
void setsum(int c){
c = sum;
}
int getx(){
return x;
}
int gety(){
return y;
}
int getsum(){
return sum;
}
private:
int x;
int y;
int sum;
int diff;
int mult;
int div;
};
int main()
{
string NB;
cout << "What you like to do ?(Sum, Difference, Multiplication or Division)\n";
cin >> NB;
if(NB == "Sum") {
Aclass Ab;
cout << "Enter Your First Number\n";
Ab.setx(cin >> a);
return 0;
}
}
You need to store the user input in a variable, then pass it to Ab.setx to store the variable in the object, i.e.
int main() {
// Declare your variables
Aclass Ab;
string choice;
int x, y;
// Get user choice
cout << "What you like to do? (Sum, Diff, Mul or Div)" << endl;
cin >> choice;
// Get user inputs
if (choice == "Sum") {
cout << "Enter your first number" << endl;
cin >> x; // Get the user input from 'cin' and store it in 'a'
cout << "Enter your second number" << endl;
cin >> y;
// Pass x, y to the Ab object and store them there
Ab.setx(x);
Ab.sety(y);
cout << "The final sum is: " << Ab.getsum() << endl;
}
return 0;
}
Note: the above code requires an implement of getsum as follows:
class Aclass{
// ...
public:
int getsum(){
return (this->x + this->y);
}
// ...
Related
#include <iostream>
using namespace std;
class Arithmetic{
private:
int x;
int y;
public:
Arithmetic(int num1, int num2){
x = num1;
y = num2;
}
Arithmetic(){
}
~Arithmetic(){
}
int getNum1(){
return x;
}
int getNum2(){
return y;
}
int add(){
return getNum1() + getNum2();
}
void showDetails(){
cout << add();
}
};
int main(){
Arithmetic a;
int num1, num2;
cout << "Enter Num1: ";
cin >> num1;
cout << "Enter Num2: ";
cin >> num2;
a.showDetails();
return 0;
}
I've been tasked to add 2 user input values using object-oriented programming in C++. I've been trying to use cin inside the main and outside the main but for some reason it won't work. Plus I've been told to not use setters and only getters. And for some reason, I still don't understand how to print showDetails().
P.S. I have no experience in C++ only in Java.
First, a mini-code review:
#include <iostream>
using namespace std; // Bad practice
class Arithmetic{
private:
int x; // Prefer default member initialization
int y;
public:
Arithmetic(int num1, int num2){
// Prefer using the initialization section
x = num1;
y = num2;
}
Arithmetic(){
// Should be defaulted and paired with default member initialization
}
~Arithmetic(){ // Unnecessary; Rule of Zero
}
int getNum1(){ // Should be const
return x;
}
int getNum2(){ // Should be const
return y;
}
int add(){
// No need to invoke getters, and should be const
return getNum1() + getNum2();
}
void showDetails(){
cout << add();
}
};
int main(){
Arithmetic a;
int num1, num2;
cout << "Enter Num1: ";
cin >> num1; // Poor formatting
cout << "Enter Num2: ";
cin >> num2;
// This is where your issue occurs. You never put the data into the object.
// Declare 'a' here, and use your parameterized constructor.
a.showDetails();
return 0;
}
Your issue is order of operations for the most part.
#include <iostream>
class Arithmetic {
private:
int x = 0;
int y = 0;
public:
Arithmetic(int num1, int num2) : x(num1), y(num2) {}
Arithmetic() = default;
int getNum1() const { return x; }
int getNum2() const { return y; }
int add() const { return x + y; }
void showDetails() const { std::cout << add(); }
};
int main() {
int num1;
int num2;
std::cout << "Enter Num1: ";
cin >> num1;
std::cout << "Enter Num2: ";
cin >> num2;
Arithmetic a(num1, num2);
a.showDetails();
return 0;
}
Output:
❯ ./a.out
Enter Num1: 5
Enter Num2: 7
12
I left the getters in, but for the question as asked, they could be deleted.
I'm trying to do multiple calculations on same 2 integer variables and display their results separately.
It works fine if I already set values to the variables.
But if I try to take input from users then it gives me random numbers instead in the output.
Here is my code in which I try to take the input/values from the user.
#include<iostream>
using namespace std;
class calculation
{
public:
calculation()
{
int num1 = 0;
int num2 = 0;
cout << "Write your numbers" << endl;
cin >> num1>>num2;
}
int sum()
{
return num1+num2;
}
int sub()
{
return num1-num2;
}
int mul()
{
return num1*num2;
}
int div()
{
return num1/num2;
}
int mod()
{
return num1%num2;
}
void displayMessage()
{
cout<<sum()<<endl<<sub()<<endl<<mul()<<endl<<div()<<endl<<mod();
}
private:
int num1,num2;
};
int main()
{
calculation obj;
obj.displayMessage();
system("Pause");
return 0;
}
The output is not correct and it just gives me random numbers instead.
But if I do it with pre set values using this code:
#include<iostream>
using namespace std;
class calculation
{
public:
calculation()
{
num1=10;
num2=5;
}
int sum()
{
return num1+num2;
}
int sub()
{
return num1-num2;
}
int mul()
{
return num1*num2;
}
int div()
{
return num1/num2;
}
int mod()
{
return num1%num2;
}
void displayMessage()
{
cout<<sum()<<endl<<sub()<<endl<<mul()<<endl<<div()<<endl<<mod();
}
private:
int num1,num2;
};
int main()
{
calculation obj;
obj.displayMessage();
return 0;
}
Then it gives the correct output.
#include<iostream>
using namespace std;
class calculation
{
public:
calculation()
{
num1 = 0;
num2 = 0;
cout << "Write your numbers" << endl;
cin >> num1>>num2;
}
int sum()
{
return num1+num2;
}
int sub()
{
return num1-num2;
}
int mul()
{
return num1*num2;
}
int div()
{
return num1/num2;
}
int mod()
{
return num1%num2;
}
void displayMessage()
{
cout<<sum()<<endl<<sub()<<endl<<mul()<<endl<<div()<<endl<<mod();
}
private:
int num1,num2;
};
int main()
{
calculation obj;
obj.displayMessage();
system("Pause");
return 0;
}
You are redeclaring a local scope in the constructor. remove the int num1 and int num2 to just num1 = 0; num2 = 0;
Also consider moving the user input outside of constructor to the main and have a constructor that takes in 2 integers.
calculation(int num1, int num2)
{
this->num1 = num1;
this->num2 = num2;
}
In your constructor:
calculation()
{
int num1 = 0;
int num2 = 0;
cout << "Write your numbers" << endl;
cin >> num1>>num2;
}
You have created two local variables names num1 and num2. They have the same names as your member variables, but they are not the same. They are new variables.
You read values into those variables, and then they are immediately destroyed when the constructor exits.
This change will use the member variables, instead of creating new variables.
calculation()
{
num1 = 0;
num2 = 0;
cout << "Write your numbers" << endl;
cin >> num1 >> num2;
}
You could also optionally use this-> to be explicit that you intend to change member variables.
calculation()
{
this->num1 = 0;
this->num2 = 0;
cout << "Write your numbers" << endl;
cin >> this->num1 >> this->num2;
}
When I run this function the sum or the product is grossly wrong. I put in 2 and 3 for the inputs and got like a negative a million. The same is for the product too. Im going to add another cout statement after i ask for which calculation they want to do to make it more natural.
#include <iostream>
#include <math.h>
#include <string>
using namespace std;
class basicCalculator {
public:
int add(int x,int y) {
return add1 + add2;
}
int multiply(int x,int y) {
return multiply1*multiply2;
}
private:
int add1;
int add2;
int multiply1;
int multiply2;
};
int main() {
cout << "What mathematical action do you want?" << endl;
cout << "Press '1' to add two numbers, '2' to multiply two numbers" << endl;
int method;
cin >> method;
int value1;
cin >> value1;
int value2;
cin >> value2;
basicCalculator bc;
switch (method) {
case 1:
cout << "The sum is " << bc.add(value1, value2) << endl;
break;
case 2:
cout << "The product is " << bc.multiply(value1, value2) << endl;
}
}
Inside your add and multiply methods you are using (uninitalized) member variables instead that the actual arguments.
Try with:
int add(int x, int y) { return x + y; }
A suggestion: add and multiply don't need an object state at all, they could be static, I don't see any reason for all the member variables you declared.
Freddy, in your functions you must use the named parameters for your calculations.
So, NOT
int add(int x,int y) {
return add1 + add2;
}
but rather
int add(int x,int y) {
return x + y;
}
Same problem with multiply.
I'm new to programming, I have been reading Sams Teach Yourself C++ in 24 hours. I just started learning classes and am confused on how to allow user input on private data. I created the following class that returns the area of a Trapezoid. Any suggestions would be greatly appreciated.
class Trapezoid
{
//assigns a number to a variable
private:
int a = 20;
int b = 25;
int height = 30;
int area;
public:
int getArea();
};
int Trapezoid::getArea()
{
// calculates the area and returns it.
area = (a + b) / 2 + height;
return area;
}
#include "AreaTrapezoid.hpp"
#include <iostream>
int main()
{
// accesses area inside the Trapeziod class.
Trapezoid areaT;
areaT.getArea();
// displays the area result
std::cout << "The area of a Trapezoid: " << areaT.getArea() << std::endl;
std::cout << system("pause");
return 0;
}
You need to read the user's input, and then expose public access to assign new values to the class's private members. For example:
class Trapezoid
{
//assigns a number to a variable
private:
int a = 20;
int b = 25;
int height = 30;
public:
int getArea();
void setA(int value);
void setB(int value);
void setHeight(int value);
};
int Trapezoid::getArea()
{
// calculates the area and returns it.
return (a + b) / 2 + height;
}
void Trapezoid::setA(int value)
{
a = value;
}
void Trapezoid::setB(int value);
{
b = value;
}
void Trapezoid::setHeight(int value)
{
height = value;
}
#include <iostream>
#include <limits>
#include <cstdlib>
#include "AreaTrapezoid.hpp"
int main()
{
Trapezoid areaT;
int value;
// get the user's input and apply it to the Trapeziod.
std::cout << "Enter A: ";
std::cin >> value;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
areaT.setA(value);
std::cout << "Enter B: ";
std::cin >> value;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
areaT.setB(value);
std::cout << "Enter Height: ";
std::cin >> value;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
areaT.setHeight(value);
// displays the area result
std::cout << "The area of the Trapezoid: " << areaT.getArea() << std::endl;
std::system("pause");
return 0;
}
Alternatively, use a constructor instead:
class Trapezoid
{
//assigns a number to a variable
private:
int a;
int b;
int height;
public:
Trapezoid(int a, int b, int height);
int getArea();
};
Trapezoid::Trapezoid(int a, int b, int height)
: a(a), b(b), height(height)
{
}
int Trapezoid::getArea()
{
// calculates the area and returns it.
return (a + b) / 2 + height;
}
#include <iostream>
#include <limits>
#include <cstdlib>
#include "AreaTrapezoid.hpp"
int main()
{
int a, b, h;
// get the user's input and apply it to the Trapeziod.
std::cout << "Enter A: ";
std::cin >> a;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cout << "Enter B: ";
std::cin >> b;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
areaT.setB(value);
std::cout << "Enter Height: ";
std::cin >> h;
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// displays the area result
Trapezoid areaT(a, b, h);
std::cout << "The area of the Trapezoid: " << areaT.getArea() << std::endl;
std::system("pause");
return 0;
}
This code produces no errors, but in the output just this line will show up then the program exits:
cout << "write 1 for areaoftrapezium and 2 for areaofrhombus and 3 for areaofParallelogram " << endl;
cin >> option;
and here the full code I don't know what is wrong
#include<iostream>
using namespace std;
class project
{
private:
float base, base2, height;
float diagonal, diagonal2;
float base3, aldtude;
public:
void trapezium() {
float areaoftrapezium;
areaoftrapezium = 0.5*(base + base2)*height;
cout << "the area of trapezium is:" << areaoftrapezium;
}
void rhombus() {
float areaofrhombus;
areaofrhombus = 0.5*diagonal*diagonal2;
cout << "the area of rhombus is:" << areaofrhombus;
}
void Parallelogram() {
float areaofParallelogram;
areaofParallelogram = base3*aldtude;
cout << "the area of Parallelogram is:" << areaofParallelogram;
}
project(int a, int b, int c){
base = a;
base2 = b;
height = c;
}
project(int d, int e) {
diagonal = d;
diagonal2 = e;
}
float getbase() {
return base;
}
float getbase2() {
return base2;
}
float getheight() {
return height;
}
float getdiagonal() {
return diagonal;
}
float getdiagonal2() {
return diagonal2;
}
float getbase3() {
return base3;
}
float getaldtude() {
return aldtude;
}
};
int main()
{
int a, b, c, d, e, f, h;
int option = 0;
project obj();
cout << "write 1 for areaoftrapezium and 2 for areaofrhombus and 3 for areaofParallelogram " << endl;
cin >> option;
switch (option) {
case '1':
{
cout << "Enter the value for two bases & height of the trapezium: " << endl;
cin >> a;
cin >> b;
cin >> c;
project obj(a, b, c);
obj.trapezium();
}
break;
case '2':
{
cout << "Enter diagonals of the given rhombus:" << endl;
cin >> d;
cin >> e;
project obj( d, e);
obj.rhombus();
}
break;
case '3':
{
cout << "Enter base and altitude of the given Parallelogram: " << endl;
cin >> f;
cin >> h;
project obj( f, h);
obj.Parallelogram();
}
break;
}
system("pause");
return 0;
}
Please tell me what I'm missing?
You are confusing numbers, like one, with digits, like '1'. They are completely different things. The number one is how many heads I have. The digit "1" is a mark that can represent the number one in the Arabic numeral system.
int option = 0;
Okay, option is an integer.
cin >> option;
And you read an integer from the user.
switch (option) {
case '1':
And then you compare it to the character 1, except you wanted to compare it to the number one.
If you read numbers from the user, compare them to numbers like one. If you read characters from the user, compare them to characters like '1'. Keep it straight.