从文本文件加载字符串后,不会对其进行相应的格式化
String is not formatted accordingly after I load it from a text file
我的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这是第二行
之后这是第一行
这是第二行
相关文章:
- std::原子加载和存储都需要吗
- 如何加载(或映射)文件部分的最大大小,但适合在Windows上的RAM
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 为什么加载SDF会导致Mobilizer创建闭环错误
- C++atioglxx.pdb未加载错误glBufferData OpenGL
- 如何使用tinyxml2从XML加载父实体和子实体
- 如何在C++中使用pybind11加载一个pickle python列表
- 系统.将数组移交给c#中动态加载的c++DLL时发生AccessViolationException
- 当我尝试加载内核模块时,如何修复C++中的这个 malloc() 错误?
- 树莓上的 Libtorch 无法加载 pt 文件,但在 ubuntu 上工作
- Python ctypes:不会按预期加载 dll
- 为什么会出现 gettnig 运行时错误:加载类型为"_Bit_type"(stl_bvector.h) 的空指针?
- 我的程序有一个保存配置文件的GUI,如何双击此配置文件以直接加载带有配置数据的GUI?
- 保存/加载大量短数组到二进制文件
- 使用 SDL2 和SDL_image C++加载图像
- 无法使用加载库卸载注入的 dll (C++)
- 是否有原子加载非原子值的函数?
- 将 bmp 文件加载到 TSpeedButton 中
- 加载格式化的二进制文件并将信息分配给结构 c++
- 从文本文件加载字符串后,不会对其进行相应的格式化