Search code examples
c++stringstream

Stringstream to string return?


So I have to write a .dot file to make a graphviz image of a sorted avl tree. Method header was provided and I have to make do with it.

Main question is how do I call the build_dot_content() method properly when it is part of std::string?

void avl::dump_dot(std::string filename){
  string s;
  ofstream fptr;
  fptr.open(filename);
  fptr<<"digraph AVL {"<<endl<<"graph [dpi=150];"<<endl<<"nodsep=0.3;"<<endl;
  fptr<<"ranksep=0.2;"<<endl<<"margin=0.1"<<endl<<"node [shape = circle fontname=\"Helvetica\"];"<<endl;
  fptr<<"edge [arrowsize=0.8]"<<endl<<endl;
  stringstream o;

  s=string build_dot_content(o, root, 1);
  fptr<<s<<endl<<"}"<<endl;

}

std::string build_dot_content(std::stringstream &o, avl_node *e, int i) {
  o<<"node"<<i<<" [label =\""<<e->element<<"\"];"<<endl;
  int iL = 2*i;
  int iR = 2*i+1;

  if(e->left != nullptr){
    o<<"node"<<i<<" -> node"<<iL<<";"<<endl;
    build_dot_content(o, e->left, iL);
  }
  if(e->right != nullptr){
    o<<"node"<<i<<" -> node"<<iR<<";"<<endl;
    build_dot_content(o, e->right, iR);
  }
  string s;
  s = o.str();
  return s;
}

Solution

  • You need to break this function up into two;

    1. Main function which is called with the node and i
    2. A second function which streams out the node only

    Call the second function from the first with the root node, and in that function recursively call itself to stream out the tree. At the end of the main function, generate the string from the stream and return it..

    -- Alternatively

    You dump function already has a stream, pass this to the build_dot_content function along with the node and index, and this can recursively stream out the elements - it should not return the string...