从文本文件加载字符串后,不会对其进行相应的格式化

String is not formatted accordingly after I load it from a text file

本文关键字:格式化 加载 文件 文本 字符串      更新时间:2023-10-16

我的CString("\r\n")中有换行符,然后将其保存到文本文件中。我不想从文本文件中重新加载字符串和控制字符,但当我显示它时,控制字符也会按原样显示,而不是创建新行。

// after I read the string from file
my_string = "This is firstlinernThis is second line";
AfxMessageBox(my_string);

这篇文章的输出是一行中的所有文本,而我期望有两行。

调试器确实显示了my_string,正如我上面指出的那样,所以字符串对象清楚地包含控制字符,但为什么strong没有相应地格式化?

使用反斜杠的转义序列在编译时而不是运行时被解析并转换为适当的字符代码。为了实现这一点,您需要处理字符串,并在从文件中加载后自己替换转义序列。下面的示例显示了一种简单的方法。

#include <iostream>
#include <string>
void replace_needle(
    std::string &haystack,
    const std::string& needle,
    const std::string& with)
{
    std::string::size_type pos;
    while((pos = haystack.find(needle)) != std::string::npos)
    {
        haystack.replace(pos, needle.size(), with);
    }
}
int main()
{
    // use double backslashes to simulate the exact string read from the file
    std::string str = "This is first line\r\nThis is second line";
    static const std::string needle1 = "\n";
    static const std::string needle2 = "\r";
    std::cout << "Beforen" << str << std::endl;
    replace_needle(str, needle1, "n");
    replace_needle(str, needle2, "r");
    std::cout << "Aftern" << str << std::endl;
}

下面是一个做同样事情的严格MFC解决方案。

int main()
{
    // use double backslashes to simulate the exact string read from the file
    CStringA str = "This is first line\r\nThis is second line";
    std::cout << "Beforen" << str << std::endl;
    str.Replace("\n", "n");
    str.Replace("\r", "r");
    std::cout << "Aftern" << str << std::endl;
}

当然,您可以替换整个"\r\n"序列,而不是每个单独的转义值。我选择了不这样做,因为我不确定你想要的灵活性有多大。两种解决方案都会产生以下输出。


之前这是第一行\r\n这是第二行

之后这是第一行
这是第二行