4

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"

4

3 回答 3

5

如果配置文件中的数据需要翻译,则必须翻译。缺少正则表达式(这显然是矫枉过正),我不知道有任何标准函数可以做到这一点。我们使用类似的东西:

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;
}

为了这。"\\r\\n", "\r\n"例如,您可以使用最后一个参数调用它。

于 2013-07-08T09:18:26.827 回答
3

听起来您的配置文件实际上包含 4 个不同的字符'\', 'r', '\', and 'n'... 您必须更改文件(例如,通过使用文件中的实际行尾来编码字符串中的行尾,即使这样,某些系统也不会发生使用 \r\n 作为他们的文本文件行分隔符),或者按照您的建议进行一些替换/翻译。翻译是更便携的方法。它也可以非常快......只需在字符串中维护两个指针/迭代器/索引 - 一个用于读取位置,一个用于写入,并在压缩转义符号时复制。

于 2013-07-08T09:13:14.840 回答
2

您不需要在代码中编写任何代码。您可以很好地读取字符以附加到来自同一配置文件的传出字符串。

假设您的 conf 文件中有名称值对:

APPEND_EOL="\n\r" str_to_send1="这是一个测试%%APPEND_EOL%%"

在发送之前解析行时,您可以生成实际行。如果您无法将 APPEND_EOL 存储在同一行中,那么您可以使用默认值从 ENV 中获取它,以防它未定义,或者可能在您的另一个配置文件中。

于 2013-07-08T09:37:47.527 回答