Alina
Alina

Reputation: 27

How to send a variable data in the omnet++?

I´m trying to send a variable data in the omnet++, but it can only send a constant data.

cMessage *msg=new cMessage(const char *s);

For example, how can I implement the following code?

data++;
cMessage *msg=new cMessage(""+data);
send(msg, "out");

Upvotes: 1

Views: 820

Answers (3)

Jerzy D.
Jerzy D.

Reputation: 7002

Using the name of message to carry data is not a good idea.
The better way is to define own message with required fields. For example this way:

  1. Create a new message file (for example DataMessage.msg) with the content:

    message DataMessage {
        int data;  
        // here one can add other fields
    }
    
  2. Add in your C++ code:

    #include "DataMessage_m.h"
    
  3. To create, set the field and send a new message use this sample code:

    DataMessage *msg = new DataMessage("DataMsg");
    msg->setData(data);
    send(msg, "out");
    

Upvotes: 3

3CxEZiVlQ
3CxEZiVlQ

Reputation: 38465

You just need to convert int type to string type and get C string from C++ string.

int data{};
cMessage *msg=new cMessage(std::to_string(data).c_str());

Upvotes: 0

Leonid
Leonid

Reputation: 738

Since data is an integer, all that is necessary is to convert it to a string. The easiest way to do this in C++ is to use std::stringstream:

std::stringstream ss;
ss << data;

Now ss.str().c_str() is of type const char *, which is accepted in cMessage's constructor.

Upvotes: 0

Related Questions