简体   繁体   English

如何在txt文件中更改EOL编码?

[英]How to change EOL coding in txt files?

I am writing in Visual Studio 2008 in C++ and I have problems with other libraries - they do not accept the line endings (EOL) I generate with my txt files. 我正在用C ++用Visual Studio 2008编写,其他库也有问题-它们不接受我用txt文件生成的行尾(EOL)。

How can I change that while writing a file with 如何在编写文件时更改它

std::ofstream myFile;
myFile.open("traindata.txt");
myFile << "stuff" << endl;
// or 
//myFile << "stuff" << '\n';
myFile.close();

EDIT 2 : 编辑2:

Ok, I did a mistake in code : I was appending "0 " for every iteration so that I had whitespace before the EOL. 好的,我在代码中犯了一个错误:我为每次迭代都添加了“ 0”,以便在EOL之前留有空格。

By bad. 糟透了 You guys have been right. 你们是对的。 Thanks for help. 感谢帮助。

Is it possible that you just don't want the \\n to end of line sequence to happen? 您是否可能不希望\\ n结束行序列? Open your file using std::ios_base::binary : this turns off precisely the conversion. 使用std::ios_base::binary打开文件:这会完全关闭转换。 ... and don't use std::endl unless you really want to flush the stream: ...除非你真的想要刷新流,否则不要使用std::endl

std::ofstream myFile("traindata.txt", std::ios_base::binary);
myFile << "stuff\n";

The close() is typically also unnecessary unless you want to check that it was successful. close()通常也是不必要的,除非您要检查它是否成功。

You should open the file stream in binary mode to keep C++ library from converting line endings automatically: 您应该以二进制模式打开文件流,以防止C ++库自动转换行尾:

myFile.open("traindata.txt", std::ios_base::out|std::ios_base::binary);

That will keep C++ library from converting '\\n' to OS-specific EOL symbol (CR-LF on Windows). 这将使C ++库不会将'\\ n'转换为特定于操作系统的EOL符号(Windows上的CR-LF)。

Download notepad++ - that should be able to fix the problem. 下载notepad ++-应该可以解决该问题。

Or dos2unix , unix2dos on cygwin 或者dos2unixunix2doscygwin

对于Windows样式的结尾,请使用myfile << "\\r\\n" ,对于UNIX样式,请使用myfile << "\\n"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM