如何解决C++ ifstream 在末尾读取一个不存在的换行符
我编写了一个基本的 C++ 程序来读取一个不包含任何换行符的单行文本文件,如下所示:
ifstream ifs;
ifs.open(filename);
char c;
int cint;
while (ifs >> noskipws >> c) {
cint = c;
cout << "'" << c << "' = " << cint << endl;
}
事情是;当它读取我想要的所有内容时,它还会在末尾读取一个不存在的换行符,其 ASCII 编号打印 10。我正在使用 g++,我删除了文件并重写了基本的测试用例,但它总是在最后得到一个换行符。可能是什么原因?
解决方法
你的输入文件末尾肯定有一个换行符
使用:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream ifs;
ifs.open("/tmp/i");
char c;
int cint;
while (ifs >> noskipws >> c) {
cint = c;
cout << "'" << c << "' = " << cint << endl;
}
return 0;
}
编译、执行:
pi@raspberrypi:/tmp $ g++ -Wall f.cc
pi@raspberrypi:/tmp $ cat > i
123
456
pi@raspberrypi:/tmp $ ./a.out
'1' = 49
'2' = 50
'3' = 51
'
' = 10
'4' = 52
'5' = 53
'6' = 54
'
' = 10
pi@raspberrypi:/tmp $ cat i
123
456
pi@raspberrypi:
我创建文件的方式在每一行的末尾放置了一个换行符,所以最后一个换行符,并且命令cat的使用也说明了这一点。
现在我添加最后一行非换行符:
pi@raspberrypi:/tmp $ echo -n "wxc" >> i
pi@raspberrypi:/tmp $ cat i
123
456
wxcpi@raspberrypi:/tmp $
pi@raspberrypi:/tmp $ ./a.out
'1' = 49
'2' = 50
'3' = 51
'
' = 10
'4' = 52
'5' = 53
'6' = 54
'
' = 10
'w' = 119
'x' = 120
'c' = 99
pi@raspberrypi:/tmp $
并且您可以看到没有意外的最终换行符被读取,并且命令 cat 的使用在文件的最后一行之后而不是单独在其行上写入提示({{1} })
还有:
wxcpi@raspberrypi:/tmp $
这意味着您创建/填充输入文件的方式在您的文件中放置了最后一个换行符,可能正在使用一个强制使用最后一个换行符的编辑器
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。