【问题标题】:String is not formatted accordingly after I load it from a text file从文本文件加载字符串后,字符串未相应格式化
【发布时间】:2013-06-25 00:54:25
【问题描述】:

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

// after I read the string from file
my_string = "This is firstline\r\nThis is second line";

AfxMessageBox(my_string);

这个输出是一行中的所有文本,而我期待两行。

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

【问题讨论】:

  • 它应该显示多行。能贴出完整的代码吗?
  • 我没有通过应用程序保存字符串,它是一个语言文件以及我在记事本中保存字符串的位置。我的应用程序只是读取字符串,我希望保存 \r\n 会创建一个新行,但它没有,如果这不是正确的方法,任何提示我如何在文本文件中的字符串中存储新行?
  • @zadane 您的意思是您实际上将四个字符 backslashlowercase-rbackslashlowercase-n 保存在记事本中?
  • @Angew 是的,我还有其他方法可以保存这些符号吗?
  • 我很困惑,因为这里的 cmets 与您在问题中所说的完全相反。但是,如果您键入字符"\r\n" 并将其保存在记事本中,即是四个字符,没有新行,它将加载为四个字符,没有新行。转义序列适用于您的源代码。如果您在源代码中键入"\r\n",编译器会将其替换为组成新行的两个字符。如果你想在记事本的文件中存储一个新行,你按回车键。

标签: c++ visual-studio mfc


【解决方案1】:

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

#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 << "Before\n" << str << std::endl;

    replace_needle(str, needle1, "\n");
    replace_needle(str, needle2, "\r");

    std::cout << "After\n" << 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 << "Before\n" << str << std::endl;

    str.Replace("\\n", "\n");
    str.Replace("\\r", "\r");

    std::cout << "After\n" << str << std::endl;
}

您当然可以替换整个“\r\n”序列而不是每个单独的转义值。我选择不这样做,因为我不确定您正在寻找的灵活性。两种解决方案都会产生以下输出。

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

【讨论】:

    猜你喜欢
    • 2023-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 2011-04-01
    相关资源
    最近更新 更多