简体   繁体   English

C ++ - 字符串中的跨平台换行符

[英]C++ - Cross-platform newline character in string

When newline in string is necessary, I use the \n character当字符串中需要换行时,我使用\n字符

 int main()
 {
     string str = "Hello world\n";
 }

Is \n crossplatform? \n是跨平台的吗? Or do I need to use macro adapting it's value with the platform?还是我需要使用宏来适应平台的价值?

Especially when str is going to be written to a file or stdout.特别是当str将被写入文件或标准输出时。

As long as you read/write text streams, or files in text mode, \n will be translated into the correct sequence for the platform.只要您在文本模式下读/写文本流或文件, \n就会被转换为平台的正确序列。

http://en.cppreference.com/w/c/io http://en.cppreference.com/w/c/io

In addition on previous answer if you need read file in Unix saved in Windows and vice-versa you may use this:此外,如果您需要在 Unix 中读取保存在 Windows 中的文件,反之亦然,您可以使用这个:

std::getline(fileName,inputStr);
inputStr.erase( std::remove( inputStr.begin(), inputStr.end(), '\r' ), inputStr.end() );
inputStr.erase( std::remove( inputStr.begin(), inputStr.end(), '\n' ), inputStr.end() );

It will delete all \r and \n .它将删除所有\r\n

Another way to put it is that \n is cross platform for the compiler.另一种说法是\n是编译器的跨平台。 It will compile on all platforms and generate correct output for the platform.它将在所有平台上编译并为平台生成正确的输出。 But the output is not really cross platform since new line in text is different on different platforms.但是输出并不是真正的跨平台,因为文本中的换行在不同的平台上是不同的。 So reading need extra handling to be platform independent.所以阅读需要额外的处理才能独立于平台。

Part of the confusion here is that a string with an \n in it is literally just that - a string with an LF byte.这里的部分混淆是其中带有\n的字符串实际上就是 - 带有 LF 字节的字符串。

The cross-platformyness comes into the equation when considering the reading and writing of streams in normal ie not binary mode.当考虑以正常(即非二进制模式)读取和写入流时,跨平台性进入等式。

Stream objects translate \n to \n , \r or \r\n depending on the platform the executable code has been compiled for.流对象将\n转换为\n\r\r\n ,具体取决于已编译可执行代码的平台。

At least this is my understand of the situation, please correct me if I am wrong about this.至少这是我对情况的理解,如果我对此有错误,请纠正我。 It isn't something I have had to worry about much in the past, since I usually exclusively write code for Linux systems.过去我不必担心太多,因为我通常专门为 Linux 系统编写代码。

Thought I should add this since the question doesn't really make sense, although I get what you are asking.认为我应该添加这个,因为这个问题并没有真正的意义,尽管我明白你在问什么。

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

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