Search code examples
c++bashmosquitto

C++: Getline ignores "\n" in mqtt message


I use a mqtt message to send messages like this: mosquitto_pub -t "TOPIC1" -m "ARG1\nARG2\n"

In my C++ application i write:

string payload = reinterpret_cast<char*>(message->payload);
std::istringstream iss(payload);
std::string arg1;
std::getline(iss, arg1);
cout << arg1 << endl;

This gives me ARG1\nARG2\n. What's wrong here?


Solution

  • This is not a C++ problem.

    Your problem is that normally \n is not interpreted as new line in by bash for a command line argument. Also mosquitto_pub will not do any interpretation on the input message.

    You can force this as follows:

    mosquitto_pub -t "TOPIC1" -m $'ARG1\nARG2\n'