c++ - 文档/规范中的哪个位置描述了如何在文本模式下将 '\n' 转换为特定于平台的行结尾?

标签 c++ language-lawyer newline std line-endings

根据经验,我知道以下代码:

#include <iostream>

int main()
{
    std::cout << "Hello World!\n";
    return 0;
}

导致在不同平台上打印不同的行结尾(例如Linux:LF,Windows:CRLF),我有时不得不 switch count to binary mode如果我想要特定的行为。同样,我知道,使用文件流我自己打开时,我必须小心地为我想要的行结束行为指定文本或二进制模式。

但是,我正在努力寻找将\n 转换为 CRLF 的行为实际上在哪里记录!

我查看了 C++ 规范(特别是 C++98 到 22)和各种在线引用资料(例如 cppreference.com),但找不到哪个类/库例程负责*实际转换 \n 进入平台特定行 end`。 (另外,不要问 ChaptGPT,它很乐意从不存在的规范中编造引用)

或者换句话说:C++ 的文本模式和二进制模式流的行为在哪里指定?

如果在 C++ 规范中找不到它,那么问题是:它是从 C 继承的行为吗?如果是的话,在哪里定义的?

或者这是 C 只是从它运行的平台继承的东西?

最佳答案

来自 C 标准,7.21.2 Streams,重点是我的:

A text stream is an ordered sequence of characters composed into lines, each line consisting of zero or more characters plus a terminating new-line character. Whether the last line requires a terminating new-line character is implementation-defined. Characters may have to be added, altered, or deleted on input and output to conform to differing conventions for representing text in the host environment. Thus, there need not be a one-to-one correspondence between the characters in a stream and those in the external representation. Data read in from a text stream will necessarily compare equal to the data that were earlier written out to that stream only if: the data consist only of printing characters and the control characters horizontal tab and new-line; no new-line character is immediately preceded by space characters; and the last character is a new-line character. Whether space characters that are written out immediately before a new-line character appear when read in is implementation-defined.

A binary stream is an ordered sequence of characters that can transparently record internal data. Data read in from a binary stream shall compare equal to the data that were earlier written out to that stream, under the same implementation. Such a stream may, however, hav e an implementation-defined number of null characters appended to the end of the stream.

C++基本上继承了这个定义。

引用您的问题的编辑:

If no documentation can be found, then a substitute answer would be knowledge of which specific API does this in the C++ stdlib, C stdlib or various OS platforms.

您正在寻找的“API”是以文本模式打开流

你写printf( "Hello Bob!\n" )std::cout << "Hello Bob!\n" ,并且库实现会执行任何必要的转换(可能不限于行结尾)。

关于c++ - 文档/规范中的哪个位置描述了如何在文本模式下将 '\n' 转换为特定于平台的行结尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76252494/

相关文章:

PDFsharp 换行符

c# - 在单独的行上动态创建标签

c++ - 内联函数模板特化

javascript - 需要了解幕后 | Node .js

c++ - 从实现中解耦类型特征定义

c++ - 类模板,在定义中引用它自己的类型

c - 字符串终止符 '\0' 与整数常量 0 的值如何相同?

javascript - 如何删除 IE 中文本框中字符串之间的 crlf

c++ - 减去无符号并得到有符号

c++ - decltype( (A{}.int_member) ) 的正确结果是什么?