0

I'm writing a set of Linked List functions with specific requirements. I must write one function with the following requirements

string retrieve_front (llheader)
retrieves the contents of the node at the front. Does not remove the node. If the list is empty, throws an exception.

with this structure definition

struct LLnode
{
    LLnode * fwdPtr; // has a pointer member
    string theData; // the data within the node
};

I really want to return the hex address of the first node in addition to the data within and Im now wondering that is possible

string retrieve_front(LLnode * theLLHeader)
{
    string data, report;

    if (theLLHeader == nullptr)
    {
        throw "This list is empty";
    }
    else
    {
        data = theLLHeader -> theData;
        report = "Front_Node[address: " + theLLHeader + " data: " + data + "]\n";
        return report;
    }
}

This is giving the following error message:

../test.cpp:103:35: error: invalid operands to binary expression ('const char *' and 'LLnode *')
                report = "Front_Node[address: " + theLLHeader + " data: " + data + "]\n";
                         ~~~~~~~~~~~~~~~~~~~~~~ ^ ~~~~~~~~~~~

I understand that a pointer is not a string (although it worked great with cout in a different function). Ive tried using static_cast to no avail and have seen some related questions when searching google but couldn't make sense of the answers. Is there a simple way to resolve this or should I just stick to returning the data alone, which is already a string?

MagicGAT
  • 135
  • 7
  • 1
    Use the `stringstream` approach from this question: https://stackoverflow.com/questions/7850125/convert-this-pointer-to-string – UnholySheep Sep 15 '19 at 20:31
  • That can be done using stringstream. See a similar problem here https://stackoverflow.com/questions/7850125/convert-this-pointer-to-string – Zukaru Sep 16 '19 at 03:02

2 Answers2

0

Here the modified version of your function.

string retrieve_front(LLnode * theLLHeader) {

string data, report;

if (theLLHeader == nullptr)
{
    throw "This list is empty";
}
else
{
    data = theLLHeader -> theData;
    stringstream ss;
    ss << theLLHeader ;
    report = "Front_Node[address: " + ss.str() + " data: " + data + "]\n";
    return report;
}

}

Ajay Gidwani
  • 121
  • 2
  • 5
0

You can use stringstream to achieve this. Inside your function add the below lines.

std::stringstream ss;
ss << "Front_Node[address: " << static_cast<const void*>(theLLHeader) << " data: " << data << "]\n";
report = ss.str();
return report;

Note: don't forget to include #include<sstream>

Vencat
  • 1,272
  • 11
  • 36