I have the following code:
#include <iostream>
using namespace std;
int a, b, sqr;
const int P = 3.14; //Later for circles...
string s1;
class MathsFunctions{
public:
virtual void square(int a, int b)=0;
};
class TriangleFunc: public MathsFunctions{
public:
void square(int a, int b){
sqr = (a * b)/2;
cout << "Square of triangle is: "<< sqr << endl;
}
};
class RectangleFunc: public MathsFunctions{
public:
void square(int a, int b){
sqr = a * b;
cout << "Square of rectangle is: "<< sqr << endl;
}
};
void getNumbers(){
cout << "Enter the first number: "<<endl;
cin >> a;
cout << "Enter the second number: "<< endl;
cin >> b;
}
void chooseTheFigure(){
cout << "Choose the figure (rectangle or triangle): "<< endl;
cin >> s1;
}
int main(){
chooseTheFigure();
getNumbers();
if(s1 == "rectangle" || "Rectangle"){
RectangleFunc r;
MathsFunctions * m = &r;
m -> square(a,b);
};
if (s1 == "triangle" || "Triangle"){
TriangleFunc t;
MathsFunctions *m = &t;
m -> square(a,b);
};
}
I created a program which is count the square of rectangle or triangle. There is a condition in main() but in the end program shows both results. How can I improve that?
Screenshot of output of the program:
This doesn't do what you think it does:
if(s1 == "rectangle" || "Rectangle"){
RectangleFunc r;
MathsFunctions * m = &r;
m -> square(a,b);
};
The if-expression above is evaluated as:
if((s1 == "rectangle") || ("Rectangle"))
// ^^^^^^^^^^^^^^^^^ or ^^^^^^^^^^
Now, the second part there, "Rectangle" is a string-literal which implicitly converts to a valid pointer. And any pointer other than nullptr or some zero like integer evaluates to true - always.
You probably meant to write:
if((s1 == "rectangle") || (s1 == "Rectangle")){
RectangleFunc r;
MathsFunctions * m = &r;
m -> square(a,b);
};
----------------------------------------
There are a few other nuances in your code, such
not having a vitual destructor in your base class and,
this:
const int P = 3.14; //Later for circles...
P will not hold the value you expect.
if(s1 == "rectangle" || "Rectangle"){
There are 2 conditions when this is true, the first is what you expect, the second is your bug because it's now what you meant to say in your code:
1) the input string s1, compared for equality to the string literal "rectangle" returns true, or
2) if the string-literal "Rectangle", by itself, is considered a true value.
As this conversion is essentially a "null pointer check", and the string literal is never null, this case is always true.
What you need is to repeat the test:
if(s1 == "rectangle" || s1 == "Rectangle"){
1.As WhiZtim pointed out, Or operator needs correction
if(s1 == "rectangle" || "Rectangle") {...}
will always be true as "Rectangle" is not null.
You should use string compare functions for strings (see strcmpi())
Edit
Regarding string functions, check this out:
Case-insensitive string comparison in C++
Related
#include <bits/stdc++.h>
using namespace std;
class point
{
public:
int x, y;
point(int a, int b)
{
x = a, y = b;
}
bool operator==(point &a)
{
if (a.x == x && a.y == y)
{
return 1;
}
else
{
return 0;
}
}
};
int main()
{
point a(5, 7), b(5, 7);
int t = a == b;
cout<<t; //it is working properly
cout<< (a==b); // it also
cout << a==b; //but it gives me compilation error
}
what is the reason...??
is there any fact of operator precedence...??
I don't know why it is giving compilation error...
as it is seen it looks fine
The << operator has higher precedence than the == operator. So this:
cout << a==b;
Is parsed as this:
(cout << a ) == b;
This causes an error because there is no overload of operator<< for cout that takes point as an argument.
The explicit parenthesis in your first example is the proper way to handle this.
I have this really simple program that's made up of 2 files.
main.cpp has the main function:
[main.cpp]
#include <iostream>
#include <string>
#include "calculator.h"
using namespace std;
int main() {
Calculator calc;
do {
string op, left, right;
float out;
cout << endl << "insert an operator and two numbers: ";
cin >> op;
if (calc.isOperator(op)) {
cin >> left;
cin >> right;
out = calc.doOp(op, left, right);
cout << endl << "result: " << endl;
}
else
cout << endl << "invalid operator" << endl;
} while(true);
}
calculator.cpp has the Calculator class and calculator.h has a declaration for the class and every function or variable in it.
[calculator.cpp]
#include <iostream>
#include <cmath>
#include <vector>
#include <string>
using namespace std;
class Calculator {
vector<float>* mem_stack;
public:
Calculator() {
mem_stack = new vector<float>();
}
~Calculator() {
delete mem_stack;
}
float memPeek() {
return (*mem_stack).back();
}
float memPeek(const int& age) {
return (*mem_stack)[(*mem_stack).size() - age];
}
float doOp(const string& op, string& left, string& right) {
float a, b;
if (left[0] == 'r') {
left = left.substr(1, left.size() - 1);
a = memPeek(stoi(left));
}
else
a = stoi(left);
if (right[0] == 'r') {
right = right.substr(1, right.size() - 1);
b = memPeek(stoi(right));
}
else
b = stoi(right);
float out;
if (op == "+")
out = a + b;
else if (op == "-")
out = a - b;
else if (op == "*")
out = a * b;
else if (op == "/")
out = a / b;
(*mem_stack).push_back(out);
return memPeek();
}
bool isOperator(const string& op) {
bool out;
out = op == "+" && op == "-" && op == "*" && op == "/";
return out;
}
};
[calculator.h]
#pragma once
#include <vector>
#include <string>
class Calculator {
private:
std::vector<float>* mem_stack;
public:
Calculator();
~Calculator();
float memPeek();
float memPeek(const int& age);
float doOp(const std::string& op, std::string& left, std::string& right);
bool isOperator(const std::string& op);
};
When I try to compile the program I get unresolved linking errors in the main function. They all look like this:
main.obj : error LNK2019: unresolved external symbol
I get them for every function from calculator.cpp called in main, including the constructor and destructor
I have looked up everything I could find on this but I still get those errors. Could anybody help me?
I'm still just a rookie.
Welcome to StackOverflow!
You may have solved this in the meantime, but your problem is pretty simple: in your Calculator.cpp file, you're basically redeclaring another Calculator class, which shadows the original one, that ends up with no functions defined for it (just the declarations in the .h file). To solve this, you instead declare your member functions with ClassName::functionName() in the .cpp instead.
Didn't try compiling, but this should work:
[calculator.cpp]
#include <iostream>
#include <cmath>
#include <vector>
#include <string>
using namespace std;
Calculator::Calculator() {
mem_stack = new vector<float>();
}
Calculator::~Calculator() {
delete mem_stack;
}
float Calculator::memPeek() {
return (*mem_stack).back();
}
float Calculator::memPeek(const int& age) {
return (*mem_stack)[(*mem_stack).size() - age];
}
float Calculator::doOp(const string& op, string& left, string& right) {
float a, b;
if (left[0] == 'r') {
left = left.substr(1, left.size() - 1);
a = memPeek(stoi(left));
}
else
a = stoi(left);
if (right[0] == 'r') {
right = right.substr(1, right.size() - 1);
b = memPeek(stoi(right));
}
else
b = stoi(right);
float out;
if (op == "+")
out = a + b;
else if (op == "-")
out = a - b;
else if (op == "*")
out = a * b;
else if (op == "/")
out = a / b;
(*mem_stack).push_back(out);
return memPeek();
}
bool Calculator::isOperator(const string& op) {
bool out;
out = op == "+" && op == "-" && op == "*" && op == "/";
return out;
}
As a side note, I don't know of your programming background, but one thing struck me out as very odd in your code. Maybe you've come from Java or C#, where you always have to initialize object member variables; C++ is a bit more like C in this respect, in that it allows you to hold objects by value, and not only reference. Which means you don't have to have a pointer to your vector<float>, nor allocate/deallocate it yourself; let the compiler do the work for you and use it by value.
So, instead of doing std::vector<float>* mem_stack;, simply do std::vector<float> mem_stack;; this makes operations like (*mem_stack).push_back(out); (or the alternative mem_stack->push_back(out);, using the -> deference operator) much cleaner: mem_stack.push_back(out);
I am trying to convert struct with boolean value into an another variable of boolean type. I am trying using static_cast and reinterpet_cast.
int main()
{
bool c,d;
struct b {
bool b1 = false;
bool b2 = false;
};
c = reinterpret_cast<uint8_t*>(&b);
d = (static_cast<uint8_t*>(static_cast<void*>(&b)));
cout <<c <<endl;
cout <<d <<endl;
return 0;
}
The error is:
main.cpp:22:38: error: expected primary-expression before ')' token
c = reinterpret_cast<uint8_t*>(&b);
^
main.cpp:23:53: error: expected primary-expression before ')' token
d = (static_cast<uint8_t*>(static_cast<void*>(&b)));
You cannot convert an instance of a struct to a bool where the value is the Boolean or of all it's members with just a cast. You need to tell the compiler how to make the object a bool and you do that by overloading the operator bool for the class. In there you do the logic to tell if it should be considered true or false. That would look like
struct Foo
{
bool a = true;
bool b = true;
bool c = false;
operator bool() { return a || b || c; }
};
int main()
{
Foo f;
std::cout << static_cast<bool>(f);
}
ouput:
1
If you have a lot of members like you said you should consider using an array instead of separate members so you can write a loop instead. C++ doesn't have reflection yet so there is no easy way to tell it to or together all the members.
If you have control over the struct definition, this might be a good place to use bit-wise logic. If you have up to 128 boolean values, you could handle them them all within a couple 64-bit vars. To check an individual boolean, you'd use a mask to only check against the intended bit. And for the case described in the question, you could do a boolean-OR operation on the 64-bit vars. something like this:
struct b {
uint64_t boolset_a;
uint64_t boolset_b;
}
So if you had defined var_b to be of type struct b, you could do this to see if any of them were true: var_b.boolset_a || var_b.boolset_b
This should, I believe, be a more efficient methodology as it will not require 100+ boolean operations to see if any of them are true.
I'd not do a cast but I'd use a member function with an explicit name:
int main()
{
struct b {
bool b1 = false;
bool b2 = false;
bool b3 = false;
bool AtLeastOneIsTrue() { return b1 || b2 || b3; };
};
b str;
str.b2 = true;
cout << str.AtLeastOneIsTrue() << endl;
str.b2 = false;
cout << str.AtLeastOneIsTrue() << endl;
}
Output
1
0
But on the other hand if your struct has 100 different bool members, the AtLeastOneIsTrue function would be terrible. An array of bool or a vector of bool would be more appropriate then.
Sample using a vector:
#include <iostream>
#include <vector>
using namespace std;
int main()
{
struct b {
vector<bool> values;
b(int numberofbools) { values.assign(numberofbools, false); }; // constructor
bool AtLeastOneIsTrue()
{
for (bool v : values)
{
if (v)
return true;
}
return false;
};
void Set(int number, bool value)
{
values[number] = value;
}
};
b str(100); // str has 100 bool values, all false
cout << str.AtLeastOneIsTrue() << endl; // print1 0
str.Set(3, true); // set value number 3 to true
cout << str.AtLeastOneIsTrue() << endl; // prints 1
}
IMHO, your better create a member function or an operator for the struct, like shown by NathanOliver, that operates on the booleans in there. In fact, your could create at least two member functions, one that tells you whether any of the booleans is true, and other that tells you if all are true.
My approach, as this will probably need to be extendable in some sense in a normal project in the future, is to use a vector of booleans, or better a map, so that each boolean can be given a name, and then two functions (methods if they belong to a bigger class, like a configuration entity) that provide the all/any computation on those flags.
A quick and dirty example of this approach is shown below (compile with C++11 activated, for the auto loop, or modify otherwise):
#include <iostream>
#include <string>
#include <map>
using namespace std;
typedef map<string, bool> Flags;
bool allOK(Flags & fl) {
bool result = true;
for (auto & kv : fl) { result &= kv.second; }
return result;
}
bool anyOK(Flags & fl) {
bool result = false;
for (auto & kv : fl) { result |= kv.second; }
return result;
}
int main(int argc, char * arg[])
{
Flags flags;
flags["a"] = true;
flags["b"] = true;
flags["the_third_flag"] = false;
cout << "1. ALL OK: " << boolalpha << allOK(flags)
<< " - ANY OK: " << anyOK(flags) << '\n';
flags["the_third_flag"] = true;
cout << "2. ALL OK: " << boolalpha << allOK(flags)
<< " - ANY OK: " << anyOK(flags) << '\n';
flags["a"] = false;
flags["b"] = false;
flags["the_third_flag"] = false;
flags["a_last_flag"] = false;
cout << "3. ALL OK: " << boolalpha << allOK(flags)
<< " - ANY OK: " << anyOK(flags) << '\n';
return 0;
}
Hey guys to start off I will say that I have looked into a lot of similar programs before posting this question and still need some help. My problem lies in the addition fraction class function where I need to add one fraction to another. I have one class and am currently working with to instances of that class (fractionObject and fractionObject2). I am storing my fractions separately, one in fractionObject and one in fractionObject2. How can I add these in my fraction class function 'Add'?
Any tips will be much appreciated! Thanks for your time!
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
// Regular prototypes
int stringToNumber(const string &Text);
int GCD(int, int);
int LCM(int, int);
class fraction{
public: // Access Specifier
int numerator;
int denominator; // Can never be 0
// Function Prototypes
fraction();
void setNumDen();
void reduce();
void add();
};
// Member functions definitions
fraction::fraction()
{
numerator = 0;
denominator = 0;
}
void fraction::setNumDen()
{
string numString;
string denString;
do{
cout << "Enter a numerator and denominator of fraction 1 separated by whitespace: ";
getline(cin, numString, ' ');
getline(cin, denString);
if (denString == "0")
cout << endl << "Please enter a number that isn't zero." << endl;
} while (denString == "0"); // Making sure denominator is not zero
numerator = stringToNumber(numString);
denominator = stringToNumber(denString);
}
void fraction::reduce()
{
int leastCommonMultiple = 0;
leastCommonMultiple = LCM(numerator, denominator);
numerator /= leastCommonMultiple;
denominator /= leastCommonMultiple;
}
void fraction::add()
{
int leastComDen;
}
int main()
{
fraction fractionObject, fractionObject2;
fractionObject.setNumDen();
fractionObject2.setNumDen();
// Reducing and displaying the reduced fractions
fractionObject.reduce();
fractionObject2.reduce();
cout << "Reduced Fraction 1 = " << fractionObject.numerator << "/" << fractionObject.denominator << "\t" << "Reduced Fraction 2 = " << fractionObject2.numerator << "/" << fractionObject2.denominator << endl;
// Adding and displaying the fractions
system("pause");
return 0;
}
// Function to convert string to number
int stringToNumber(const string &Text)//Text not by const reference so that the function can be used with a
{ //character array as argument
stringstream ss(Text);
int result;
return ss >> result ? result : 0;
}
// result=GCD(a,b)
int LCM(int a, int b) {
int temp = 0;
while (b != 0) {
temp = b;
b = a%b;
a = temp;
}
return a;
}
// result=LCM(a,b);
int GCD(int a, int b) {
int result = 0;
result = a * (b / LCM(a, b));
return result;
}
No complete answer here, but add should have two const fraction& arguments and return a temporary fraction object. You might rename it operator+. Many libraries add a += operator that doesn't require making a temporary object. C++11 allows you to reduce the overhead of these temporary objects with a move constructor.
As for the implementation, here’s a hint: 1/6 + 1/9 = (9+6)/54 = 5/18. I notice you already have a reduce function.
So I've made for myself a point printing class, that is supposed to have the user enter in 2-tuples; that is, x and y, that then prints them back to the user in ^order,^ where order means p1=(x,y)
#include <iostream>
#include <vector>
#include <string>
#include <cmath>
#include <algorithm>
using namespace std;
class Point2D {
public:
Point2D();
Point2D(double a, double b);
double getx();
double gety();
void setx(double a);
void sety(double b);
virtual void print();
virtual void print(int a);
double angle();
private:
double x;
double y;
};
bool operator<( Point2D a , Point2D b );
int main() {
double my_x=-999;
double my_y=-999;
string my_color;
double my_weight;
vector<Point2D*> points;
cout << "Welcome to Point Printer! Please insert the x-and y-coordinates for your points and I will print them in sorted order! Just one rule, the point (0,0) is reserved as the terminating point, so when you are done enter (0,0).\n";
while(true)
{
cout << "x = ";
cin>>my_x;
cout << "y = ";
cin>>my_y;
if((my_x == 0)&&(my_y==0))
{
break;
}
points.push_back(new Point2D(my_x, my_y));
}
sort(points.begin(), points.end());
cout << "\n\n";
cout << "Your points are\n\n";
for(int i=0;i<points.size();i++)
{
cout<<i+1<<": ";
(*points[i]).print(); cout<<endl; // this is the printing gadget
}
for(int i=0; i<points.size(); i++)
{
delete points[i];
}
cout << endl << endl;
return 0;
}
double Point2D::angle()
{
double Angle = atan2(y,x);
if(Angle < 0)
{
return Angle + 3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679;
}
return Angle;
}
bool operator< (Point2D a, Point2D b)
{
if (a.getx()*a.getx()+a.gety()*a.gety() < b.getx()*b.getx()+b.gety()*b.gety())
{
return true;
}
else if (a.getx()*a.getx()+a.gety()*a.gety() > b.getx()*b.getx()+b.gety()*b.gety())
{
return false;
}
if (a.getx()*a.getx()+a.gety()*a.gety() ==b.getx()*b.getx()+b.gety()*b.gety())
{
if (a.angle() < b.angle())
{
return true;
}
else if (a.angle() > b.angle())
{
return false;
}
}
return true;
}
Point2D::Point2D() { x = 0; y = 0; return;}
Point2D::Point2D(double a, double b) { x = a; y = b; return;}
double Point2D::getx() { return x;}
double Point2D::gety() { return y;}
void Point2D::setx(double a) { x = a; return; }
void Point2D::sety(double b) { y = b; return; }
void Point2D::print() {
cout<<"("<<x<<","<<y<<")";
return;
}
void Point2D::print(int a) {
print(); cout<<endl;
}
What I'm having trouble with is either one of the following:
sort
angle()
operator<(Point2D a, Point2D b)
Something different entirely...
In particular, the following points:
x = 1
y = 2
x = 2
y = 3
x = 1.1
y = 2.2
x = -10
y = 10
x = -5
y = -3
x = -5
y = 3
x = 5
y = -3
x = 5
y = 3
x = 0
y = 0
are not sorted in the correct order.
Any help would be much appreciated. Thank you.
The problem (or one of them) is the final statement in your comparison function.
return true;
Look at this block:
if (a.getx()*a.getx()+a.gety()*a.gety() ==b.getx()*b.getx()+b.gety()*b.gety())
{
if (a.angle() < b.angle())
{
return true;
}
else if (a.angle() > b.angle())
{
return false;
}
}
First of all, if we've gotten to this point, we've determined that the (x*x + y*y) calculations for both a and b are equal. Now let's assume that the angle is also equal. What happens? The first test fails because a.angle() is not less than b.angle(). Then the second test fails because a.angle() is not greater than b.angle(). Then you return true. In other words, you're saying that it is true that a is less than b, even though by all rights, they should be considered equal, and so you should return false. Instead of multiple tests on the angle, you can just return a.angle() < b.angle();, and that should do the trick. With some additional simplifications, your function should look something like this:
bool operator<(Point2d a, Point2d b)
{
double A = a.getx()*a.getx()+a.gety()*a.gety();
double B = b.getx()*b.getx()+b.gety()*b.gety();
if (A < B) return true;
if (A > B) return false;
return a.angle() < b.angle();
}
The problem is probably that you are storing and sorting pointers, not objects. The points will be compared not with your operator but their addresses. Try change points to vector<Point2d>
First of all just use (if your are just planning to sort 2D points) :
(Edit : See Benjamin Lindley comments below.)
bool operator < ( Point2D a, Point2D b)
{
return a.getx() < b.getx() ||
(a.getx()==b.getx() && a.gety()< b.gety() );
}
Another thing if use use std::cout in operator < ( Point2D a, Point2D b), you will notice it won't be called anytime.
The reason is this:
vector<Point2D*> points; // Vector of Point2D*
but bool operator< (Point2D a, Point2D b) is used for comparision.
Suggested Fixes:
vector<Point2D> points;
points.push_back(Point2D(my_x, my_y));
And accordingly, wherever applicable.
Also you can't define anything like
bool operator<(const Point2D* a, const Point2D* b)
Because of this:
C++03 standard, §13.5 [over.oper] p6:
An operator function shall either be a non-static member function or
be a non-member function and have at least one parameter whose type is
a class, a reference to a class, an enumeration, or a reference to an
enumeration.