0

I want to convert a Node object from yaml-cpp to a std::string. I keep getting an error that says it cannot find the right overloaded operator <<. Here's my code:

#include <iostream>
#include <string>
#include <yaml-cpp/yaml.h>

using namespace std;

int main(int argc, char* argv[]) {
    YAML::Node myNode;
    myNode["hello"] = "world";
    cout << myNode << endl; // That works but I want that not to stdout

    string myString = "";
    myNode >> myString; // Error at this line
    cout << myString << endl;
    return 0;
}

The error is

src/main.cpp:13:12: error: invalid operands to binary expression ('YAML::Node' and 'std::string' (aka 'basic_string<char, char_traits<char>, allocator<char>>')
[somefile] note: candidate function template not viable: no known conversion from 'YAML::Node' to 'std::byte' for 1st argument
  operator>> (byte  __lhs, _Integer __shift) noexcept
  ^
[A bunch of these 10+]

Using clang++ -std=c++20 -I./include -lyaml-cpp -o prog main.cpp

Please help me find out!

3
  • Does this node type have an operator>> that takes a string? Commented Sep 25, 2022 at 17:30
  • 1
    Use std::stringstream? Or boost::lexical_cast? Commented Sep 25, 2022 at 17:33
  • std::stringstream worked. Thanks Commented Sep 25, 2022 at 17:38

1 Answer 1

1

Actually needed to create an stringstream and then convert it to an normal string:

#include <iostream>
#include <string>
#include <yaml-cpp/yaml.h>

using namespace std;

int main(int argc, char* argv[]) {
    YAML::Node myNode;
    myNode["hello"] = "world";

    stringstream myStringStream;
    myStringStream << myNode;
    string result = myStringStream.str();

    cout << result << end;
    return 0;
}

Output:

hello: world
Sign up to request clarification or add additional context in comments.

1 Comment

You should use std::ostringstream instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.