So the problem was this
error: invalid operands of types ‘const char [20]’ and ‘float’ to binary ‘operator<<’
that came out on my string fuction. I tried searching up in google but nothing came up.
#include <iostream>
#include <string>
using namespace std;
class Rectangle
{
public:
Rectangle () : length(1.0), width(1.0)
{
}
Rectangle(float l, float w) :length(l), width(w)
{
}
void setLength(float l)
{
length = l;
}
float getLength()
{
return length;
}
void setWidth(float w)
{
width = w;
}
float getWidth()
{
return width;
}
double getArea()
{
return width * length;
}
double getPerimeter()
{
return 2 * (width + length);
}
string toString()
{
string s1 = "Rectangle [Length ="<<getLength()<<", width = "<<getWidth()<<"]";
return s1;
}
private:
float length = 1.0;
float width = 1.0;
};
Here's my code. So what is the problem in my string fuction? PS. also, it would be great if you point out the other problems that I missed.
You're probably mixing printing to an output stream via <<
with concatenating strings.
To concatenate 2 std::string
s, you use the +
operator instead. The operator also can work with things similar to a string like char const*
, but only if one of the operands already is a std::string
.
Use std::to_string
for converting the numbers to string representation:
std::string toString()
{
std::string s1 = "Rectangle [Length =" + std::to_string(getLength()) + ", width = " + std::to_string(getWidth()) + "]";
return s1;
}
Alternatively use std::ostringstream
to create the string allowing you to use the <<
operator:
#include <sstream>
#include <utility>
...
std::string toString()
{
std::ostringstream stream;
stream << "Rectangle [Length =" << getLength() << ", width = " << getWidth() << "]";
return std::move(stream).str();
// note: str on a rvalue reference may be cheaper starting C++20
// in prior versions the line above equivalent to
// return stream.str();
}