繁体   English   中英

C和Java语言中的换行符

[英]New line character in c and java language

现在,行分隔符取决于系统,但是在ac程序中,我使用'\\ n'作为行分隔符,无论我在Windows还是linux中运行它,都可以正常工作。 为什么??

在Java中,我们必须使用%n,因为它与系统有关,那么无论在哪个OS中运行它,为什么我们都在c中使用'\\ n'作为换行符?

这是C99标准必须说的:

5.2.2 Character display semantics
[...]
2. Alphabetic escape sequences representing nongraphic characters in the execution
character set are intended to produce actions on display devices as follows:
[...]
\n (new line) Moves the active position to the initial position of the next line.

这意味着,如果要打印“ \\ n”,则必须在Windows上将其更改为“ \\ r \\ n”才能满足此要求。 但这仅是针对显示设备而不是文件定义的。 没有关于如何在文本文件中表示此(或任何其他空格)字符的规范,但是:

5.2.2 Character display semantics
[...]
3. Each of these escape sequences shall produce a unique implementation-defined value
which can be stored in a single char object. The external representations in a text file
need not be identical to the internal representations, and are outside the scope of this
International Standard.

因此,对您的问题的直接答案是-它可以按您期望的方式工作,因为C标准在打印到显示设备或存储在文本文件中时没有说明\\n字符的二进制表示。 但是,它确实精确指定了打印时的行为-应该移至下一行的开头

在C程序中,指定打开文件时是文本文件还是二进制文件-使用fopen打开文件时,指定模式字符串,如果这是二进制文件,则该字符串包括b 在读取和写入文本模式文件时,C库将自动在'\\n'字符和系统行分隔符之间转换。

在Java中,没有类似的“文本模式”会自动为您翻译,因此要处理行分隔符,您需要在代码中显式地进行处理。

暂无
暂无

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

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