PDA

View Full Version : Int to String - manipulating string



mickey
3rd November 2007, 21:37
Hello, I have to wirte this method and I'd like one efficent and compact:


int _low, _high;
std::string MyClass:: print() {
std::string str;
std::string result;
std::stringstream ss;

result += "[";
ss << _low;
ss >> str;
result += str;

result.append("-");

ss << _high;
ss >> str;
result += str;
result.append("]");
return result;
}
//main
MyClass mycl;
cout << " The range is: " << mycl.print() << endl

it must print: "the range is [10-20]"

It seems too large and not compact.... How can I improve?
Thanks.

DeepDiver
3rd November 2007, 21:48
Implement an output stream operator for your class like this:


inline std::ostream& operator<<(std::ostream& os, const MyClass& c)
{ return os << "[" << c.low() << "-" << c.high() << "]"; }


In action:


MyClass mycl;
cout << " The range is: " << mycl << endl;

mickey
4th November 2007, 00:35
hello, thanks but I had an error like this:
error C2804: binary 'operator <<' has too many parameters

wysota
4th November 2007, 09:06
Did you implement it as a method of your class or as a standalone function? It should be the latter.

mickey
4th November 2007, 12:36
Did you implement it as a method of your class or as a standalone function? It should be the latter.
I had to declare it as friend method.....because my situation was it:


//subnode.cpp
class SubNode {
protected:
int _low, _high;
}

//node.cpp
class Node : SubNode {
........
int other;

};
friend inline std::ostream& operator<<(std::ostream& os, const Node& n) {
return os << "[" << n._low << "-" << n._high << "]";
}
//end node.cpp

If I declare the inline function in node.cpp but after class declaration ( after "};" ) it gets an error that it can't acces to protected member.
Is it ok in this way or I can be better?

wysota
5th November 2007, 09:25
It has to be a standalone function, not a method. If you want it to be a method of your class, you have to omit the second parameter (const Node& n).

mickey
5th November 2007, 20:11
Hi, I declared it as below. it seem works both them


//subnode.cpp
class SubNode {
protected:
int _low, _high;
}

//node.cpp
class Node : SubNode {
........
int other;
friend std::ostream& operator<<(std::ostream& os, const Node& n) {
return os << "[" << n._low << "-" << n._high << "]";
}
};
//inline std::ostream& operator<<(std::ostream& os, /*const*/ Node& n) {
// return os << "[" << n.GETLOW() << "-" << n.GETHIGH() << "]";
// }
//end node.cpp

Out of class 'const' gets error; idem for _low and _high that I coudn't access them because they are protected....