0

We can print elements of a structure using structure.element. But I want to print a complete structure at once.

Is there a method something like cout<<strucutre, the same way we can print a list or tuple in Python.

This is what I want:

struct node {
  int next;
  string data;
};

main()
{
  node n;
  cout<<n;
}
Rishi Chauhan
  • 13
  • 1
  • 4

2 Answers2

0

Yes. You should override the << operator for the object cout. But cout is an object of class ostream so you cannot just simply overload the << operator for that class. You have to use a friend function. The function body would look like this:

friend ostream& operator<< (ostream & in, const node& n){
    in << "(" << n.next << "," << n.data << ")" << endl;
    return in;
}

The function is friend, in case if you have private data in your class.

0

You need to overload the << operator properly:

#include <string>
#include <iostream>
struct node {
    int next;
    std::string data;
    friend std::ostream& operator<< (std::ostream& stream, const node& myNode) {
        stream << "next: " << myNode.next << ", Data: " << myNode.data << std::endl;
        return stream;
    }
};

int main(int argc, char** argv) {
    node n{1, "Hi"};

    std::cout << n << std::endl;
    return 0;
}
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97