ofstream 在 Windows7 中不打印换行符到 txt
当我想打印 \n
时遇到一些问题,我正在使用 endl
来打印。问题是当我在 Windows7 上运行代码时,它不会打印出换行符。但在 Ubuntu 中它会打印出换行符。两个操作系统都使用相同的编译器 GNU g++。
所以我想知道是否有一些不同的方法可以在 Windows 中将换行符打印到文件中?
void translate(ofstream &out, const string &line, map<string, string> m)
{
stringstream ss(line);
string word;
while(ss >> word)
{
if(m[word].size() == 0)
out << "A";
else
out << m[word] << " ";
}
out << "\n";
}
I have some issue when I want to print out \n
I'm using endl
for that. And the problem is when I run the code on Windows7 it won't print out the newline. But it will print out newline in Ubuntu. Both OS is using the same compiler GNU g++.
So I wonder if there are some different way to print newline to file in Windows?
void translate(ofstream &out, const string &line, map<string, string> m)
{
stringstream ss(line);
string word;
while(ss >> word)
{
if(m[word].size() == 0)
out << "A";
else
out << m[word] << " ";
}
out << "\n";
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
输出 '\n' 或使用 endl 将产生完全相同的内容(唯一的区别是 endl 也会刷新)。当写入 \n 字符时,如果文件处于“文本模式”,运行时库会将其转换为平台的本机机制来指示行。在 unix 上,这是不必要的,因为该机制是 \n 字节。在 Windows 上,\n 变为 \r\n(回车、换行)。我怀疑您知道所有这些,但我正在回顾以防万一。
简而言之,只要您的运行时库是针对 Windows 设置的,您拥有的代码就会按您的预期工作。我怀疑您正在使用 cygwin 的 g++ 或其他一些 g++ 端口,它们不是为 Windows 样式行设置的,即使在文本模式下也是如此。某些编辑器无法正确解释未翻译的\n。
Outputting either '\n' or using endl will result in the exact same content (the only difference is endl also flushes). When that \n character is written, if the file is in "text mode", the runtime library converts it to the platform's native mechanism to indicate lines. On unix, this is unnecessary because that mechanism is a \n byte. On Windows, that \n becomes \r\n (carriage return, line feed). I suspect you know all of this, but I'm reviewing it just in case.
In short, as long as your runtime library is setup for Windows, the code you have will work as you expect. I suspect you are using cygwin's g++, or some other g++ port, that is not setup for Windows-style lines, even in text mode. Some editors will not correctly interpret that untranslated \n.