-
reset a stringstream
I googled and googled, but i can't get any of the recommedations to work:
i'm trying to cout a graph in a formated way,
it work fine for the first vertex, (prints all the outgoing edges, but when i get to the second one, the stringstream doesnt accecpt more data) how do I reset it???
Code:
std::ostream& operator << (std::ostream & out,const Graph & g2)
{
std::string str="anything_quite_long";
stringstream sstream;
Node* current=g2.m_list->getHead();
bool flag=false;
//print list of vertices
out << '|' << *(g2.m_list) << '|';
//go through list of edges
while (current!=NULL)
{
////prints all edges for current vertex
sstream << *current;
if (sstream >> str && flag==false)
{
out << *current;
flag=true;
}
else if (sstream >> str)
out << ',' << *current;
current=current->getNext();
/* the following are some the ways I tried to reset the stream!!
sstream.clear();
sstream.seekp(0);
sstream << '\0';
}
out << '|';
return out;
-
Move the sstream variable declaration inside the while-loop, that way you get a "new" stringstream each time.
--
Mats
-
good idea!!!
thanks a million
-
another option, which I use all the time is to use the str() member function of stringstream.
Code:
std::stringstream ss;
ss << "Hello, World";
std::cout << ss.str() << std::endl; // with no arguments stringstream::str() returns the string as an std::string
ss.str("foo"); // with a const char* argument, it sets the stringstream to the indicated value, which could be an empty string ("")
std::cout << ss.str() << std::endl;