在每个文件的末尾是否总是有一个新的行字符( ) ?
Is there always a new line character ( ) in the end of every file?
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream inStream("input.txt");
char next;
inStream.get(next);
while(! inStream.eof( ))
{
cout << (int) next << " ";
inStream.get(next);
}
return 0;
}
文件"input.txt":
ab
c
理论上,正好有四个字符'a', 'b', 'n', 'c'(我自己打的)
但实际上,上述程序的输出是:'a', 'b', 'n', 'c', 'n'。
有人能帮我吗?
我假设您在linux中编辑input.txt,大多数linux编辑器在最后一行末尾附加LF字符。
Windows使用CRLF (rn, 0D 0A)行结尾,而Linux/Unix只使用LF (n, 0A)。
如果您不希望发生这种情况,在windows上编辑文件并将文件复制到linux并执行相同的操作,而不更改任何代码。我用两种方法执行代码,得到以下输出
在Linux上编辑input.txt
时。97 98 10 99 10
当input.txt
在Windows上编辑并复制到Linux时。97 98 13 10 99
不,不能保证文件以n
或任何字符结束,甚至是ASCII EOF
字符(这对我来说没有意义)。文件只是一个任意字节流。你可以有零字节的文件,1字节的文件,2字节的文件,等等,而不确定这些字节是什么。
文件通常以n
结尾,因为它们是在这样的循环中编写的:
for(int i=0;i<numberOfLines;i++) {
fs << getSomeText( i ) << endl;
}
fs.close();
注意endl
,它将导致每行,包括最后一行,以n
结尾。
当然,在Windows上是rn
,而老派的Mac操作系统是r
,只是为了尴尬。
相关文章:
- 有一个打印语句的函数是一种糟糕的编程实践吗
- VSCode-有一个红色下划线,但程序构建和运行正确,并且出现配音错误
- 如果有一个模板构造函数只有一个泛型参数,为什么我必须有一个复制构造函数
- 有没有可能有一个只有ADL才能找到的非好友功能
- 使用.find函数在c++中查找字符和另一个字符之间的大小
- 我有一个对象,它将在整个程序的持续时间内实例化,但一个类成员不会,我应该动态分配它吗?
- 我的程序有一个保存配置文件的GUI,如何双击此配置文件以直接加载带有配置数据的GUI?
- 将超出范围的整数分配给有符号字符类型
- 在学习数据结构之前对STL有一个了解是好的吗?
- 我在 .h 中有一个枚举类,并且在.cpp错误中有一个运算符重载:与"运算符<<不匹配
- 如何在 Gnuplot 中分别绘制 2 个文件数据?我有一个文件"sin.txt",另一个文件"cos.txt",我想将它们分别绘制在一个图表上
- 有可能在同一个字符序列上有一个类似函数的宏和一个类似对象的宏吗
- 有没有办法在不知道它的大小的情况下制作一个字符数组
- 有没有一种方便的方法可以通过一些Qt小部件只输入一个字符
- Qt GUI设计-是否有一个不可见的字符适合标签文本
- Python/ c++ /Java:是否有一个库可以识别字符并告诉我它们在图像中的位置
- 我有一个字符数组,我想把它的二进制位向右移动一个
- 为什么我用WriteFile写入文件的每个字符之间都有一个空白
- 在每个文件的末尾是否总是有一个新的行字符( ) ?
- 使用c++,在制作控制台应用程序时,是否有一种方法可以让cin接受输入的下一个字符并在不按回车键的情况下继续