endl不适用于wstring(unicode) [英] endl doesn't work with wstring (unicode)

查看:96
本文介绍了endl不适用于wstring(unicode)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是代码:

  std::ofstream f("file1.txt");
  f<<"123"<<std::endl<<"456";           //(*1)

  /*std::stringstream ordinary_strstream; This works too
  ordinary_strstream<<"123"<<'\n'<<"456";
  f<<ordinary_strstream.str();*/

  std::wstringstream s;
  s<<L"123"<<std::endl<<L"456";         //(*2)
  s<<L"123"<<L"\n"<<L"456";             //(*3) 
  s<<"123"<<WCHAR(13)<<WCHAR(10)<<"456";//(*4)

  HANDLE h =CreateFileW(L"file2.txt", GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE,
    NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

  ULONG l;
  WriteFile(h, s.str().c_str(), s.str().length() * 2, &l, NULL);

在(* 1)情况下有换行符,在(* 2)和(* 3)中没有file2.txt文件中的换行符.在(* 3)中有一个换行符.我使用notepad.exe进行浏览.十六进制编辑器不显示0x0D字节,仅显示0x0A.

In the (*1) case there is a newline, in the (*2) and (*3) i see no newline in the file2.txt. In the (*3) there is a newline. I use notepad.exe for browsing. Hex editor shows no 0x0D byte, only 0x0A.

我应该如何正确地将换行符放在unicode文本文件中?谢谢.

How should i properly put the newline in unicode text file? Thank you.

推荐答案

这是预期的:std::endlL'\n'写入宽字符流(并将其刷新,但是在这里不相关),从不L"\r\n" .在编写文字L"\n"时更明显. WriteFile不执行任何类型的换行替换,wstringstream也不执行(请注意,在文本模式下打开文件流时,将执行换行替换,这就是为什么您在(*1)).因此,在文件中将没有回车符.如果需要它们,请明确地编写它们.

That's expected: std::endl writes a L'\n' to a wide-char stream (and flushes it, but it's not relevant here), never L"\r\n". It's even more obvious when writing a literal L"\n". WriteFile doesn't perform any kind of newline substitution, neither does wstringstream (note that file streams do perform newline substitution when opened in text mode, and that's why you get a proper newline in (*1)). Therefore, in the file there will be no carriage return characters. If you want them, write them explicitely.

这篇关于endl不适用于wstring(unicode)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆