c++gnuplotgnuplot-iostream

how to use variables in C++ in the gnuplot-iostream


I am using gnuplot-iostream for c++,my problem is like below:

 gp << "set object 1 rect from 3,1 to 3.2,4 fc lt 1 \n";

In the numbers of above, can we use some variables in c++ to replace them? and how to do that? Adding one rectangle is easy, but when I want to add more, that will be very intractable. I try several ways ,but it does not work. Thanks ahead!


Solution

  • Never used gnuplot-iostream, but maybe some vanilla C++ will help you, iostream is just a pipe to console, so you cant interrupt the buffer but concatenate information, you could do something like this:

     gp << "set object " << 1 << " rect from "
     << 3,1 << " to " << 3.2 << "," << 4 << " fc lt 1 \n";
    

    But i suppose you don't want to do that.

    I'd create a struct and overload the << operator to return whatever you need.

    struct Rect {
      float from[2];
      float to[2];
    }
    std::ostream& operator<<(std::ostream& os, const Rect& obj)
    {
        std::string formated = "from "
          + std::to_string(obj.from[0]) + ","
          + std::to_string(obj.from[1]) + " to "
          + std::to_string(obj.to[0])   + ","
          + std::to_string(obj.to[1]);
    
        os << formated;
        return os;
    }
    

    So you can just define rectangles and pass them to the stream

    Rect r1 = {{2,41},{63,1.4}};
    std::cout << r1; // "from 2,41 to 63,1.4"