majintao0131 / yaml-cpp

Automatically exported from code.google.com/p/yaml-cpp
MIT License
0 stars 0 forks source link

Add output (extraction) operator #50

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
add:

        friend std::ostream& operator << (std::ostream& out, const Node& node);

in node.h

and add:

    inline std::ostream& operator << (std::ostream& out, const Node& node) {
        std::string scalar;
        if(!node.GetScalar(scalar))
            throw InvalidScalar(node.m_mark);

        out << scalar;

        return out;
    };

in nodeimpl.h

Original issue reported on code.google.com by PlasticC...@gmail.com on 20 Oct 2009 at 10:17

GoogleCodeExporter commented 9 years ago
Sorry I'm not sure how to make this an enhancement rather than a defect... I've 
not
used this google code setup much.

Original comment by PlasticC...@gmail.com on 20 Oct 2009 at 10:18

GoogleCodeExporter commented 9 years ago
It's all right :)

Actually, the intended way to do this is to use the emitter. Try:

    YAML::Emitter emitter;
    emitter << node;
    std::cout << emitter.c_str();

This way includes the ability to output any type of node (not just a scalar). If
you're *only* interested in outputting scalar nodes, then I recommend just 
writing
your own function to do that, since it's a little off the beaten track.

Thanks for the interest!

Original comment by jbe...@gmail.com on 21 Oct 2009 at 2:25

GoogleCodeExporter commented 9 years ago
By the way, I've considered writing your function, implemented with the above 
code,
but I feel that output to a stream that may contain a newline is a little 
subtle, and
should be done by the coder explicitly.

For example, if you can just write

    std::cout << node;

it may feel like you can use this outputting in a formatted way, such as:

    std::cout << "**** " << node << "\n";

which could output

    **** - math
    - science
    - English

which wouldn't be a valid YAML file.

Original comment by jbe...@gmail.com on 21 Oct 2009 at 2:30