简体   繁体   English

C和Java语言中的换行符

[英]New line character in c and java language

Now line separator is system dependent but while in ac program i use '\\n' for line separator , it works fine whether i run it in windows or linux . 现在,行分隔符取决于系统,但是在ac程序中,我使用'\\ n'作为行分隔符,无论我在Windows还是linux中运行它,都可以正常工作。 why ?? 为什么??

In java we have to use %n as it is system dependent then how come we use '\\n' in c for new line irrespective of os in which we run it ? 在Java中,我们必须使用%n,因为它与系统有关,那么无论在哪个OS中运行它,为什么我们都在c中使用'\\ n'作为换行符?

Here's what C99 standard has to say about it: 这是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.

This means that if you print "\\n", it has to be changed to "\\r\\n" on windows in order to fulfill this requirement. 这意味着,如果要打印“ \\ n”,则必须在Windows上将其更改为“ \\ r \\ n”才能满足此要求。 But this is only defined this way for display devices, not for files. 但这仅是针对显示设备而不是文件定义的。 There is no specification on how this (or any other whitespace) character should be represented in text-file , however: 没有关于如何在文本文件中表示此(或任何其他空格)字符的规范,但是:

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.

So the direct answer to your question is - it works as you would expect because the C standard does not say anything about binary representation of \\n character when it's printed to the display device or stored in text-file. 因此,对您的问题的直接答案是-它可以按您期望的方式工作,因为C标准在打印到显示设备或存储在文本文件中时没有说明\\n字符的二进制表示。 It does, however, precisely specify how it should behave when printed - it should move to the beginning of next line. 但是,它确实精确指定了打印时的行为-应该移至下一行的开头

In C programs, you specify when you open the file whether it is text or binary -- when you open a file with fopen , you specify a mode string, which includes b if this is a binary file. 在C程序中,指定打开文件时是文本文件还是二进制文件-使用fopen打开文件时,指定模式字符串,如果这是二进制文件,则该字符串包括b When reading from and writing to text-mode files, the C library will automatically translate between '\\n' characters and the system line separator. 在读取和写入文本模式文件时,C库将自动在'\\n'字符和系统行分隔符之间转换。

In java, there is no analogous "text mode" that automatically translates for you, so to deal with line separators, you need to do it explicitly in your code. 在Java中,没有类似的“文本模式”会自动为您翻译,因此要处理行分隔符,您需要在代码中显式地进行处理。

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

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