Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Carriage return and line feed in a string

I am working with the communication for some TCP/IP connected equipment in C++. The equipment requires that the commands sent are ended with \r\n.

I am using a configuration file from which I am reading the commands used in the communication.

The problem I have is that the commands \r\n are interpreted as the 4 characters they are and not as carriage return and line feed.

I have tried to use the string.data() but I get the same result as string.c_str().

Is there any nice function to get it correct from the beginning or do I have to solve this with a normal replace function? Or some other way that I have not thought about?

I guess, if I don't find a really neat way to do this I will just omitt the \r\n in the configuration file and add it afterwards, but it would be nice to have it all in the configuration file without any hard coding. I think I would need to do some hard coding as well if I would try to replace the four characters \r\n with their correct characters.

Thanks for any help

Edit: The config file contains lines like this one.

MONITOR_REQUEST = "TVT?\r\n"

like image 934
user1728363 Avatar asked Dec 26 '22 00:12

user1728363


1 Answers

If the data in the configuration file requires translation, you have to translate it. Short of regular expressions (which are clearly overkill for this), I don't know of any standard function which would do this. We use something like:

std::string
globalReplace(
    std::string::const_iterator begin,
    std::string::const_iterator end,
    std::string const& before,
    std::string const& after )
{
    std::string retval;
    std::back_insert_iterator<std::string> dest( retval );
    std::string::const_iterator current = begin;
    std::string::const_iterator next
            = std::search( current, end, before.begin(), before.end() );
    while ( next != end ) {
        std::copy( current, next, dest );
        std::copy( after.begin(), after.end(), dest );
        current = next + before.size();
        next = std::search( current, end, before.begin(), before.end() );
    }
    std::copy( current, next, dest );
    return retval;
}

for this. You could call it with "\\r\\n", "\r\n" for the last to arguments, for example.

like image 140
James Kanze Avatar answered Jan 08 '23 21:01

James Kanze