我正在读取这样的文件:
char string[256];
std::ifstream file( "file.txt" ); // open the level file.
if ( ! file ) // check if the file loaded fine.
{
// error
}
while ( file.getline( string, 256, ' ' ) )
{
// handle input
}
仅出于测试目的,我的文件只有一行,末尾有一个空格:
12345
我的代码首先成功读取12345。但随后它不是循环结束,而是读取另一个字符串,这似乎是一个返回/换行符。
我已将我的文件保存在gedit
and in nano
。我也用Linux输出了它cat
命令,最后没有返回。所以文件应该没问题。
为什么我的代码读取返回/换行符?
Thanks.
首先确保您的输入文件是好的:
运行以下命令并让我们知道输出:
#include <iostream>
#include <sstream>
#include <string>
#include <iterator>
#include <fstream>>
#include <iomanip>
#include <algorithm>
int main()
{
std::ifstream file("file.txt");
std::cout << std::hex;
std::copy(std::istreambuf_iterator<char>(file),
std::istreambuf_iterator<char>(),
std::ostream_iterator<int>(std::cout, " "));
}
Edit:
输出为 31 32 33 34 35 20 0A
尝试运行此代码并查看输出是什么:
#include <iostream>
#include <sstream>
#include <string>
#include <iterator>
#include <fstream>>
#include <iomanip>
#include <algorithm>
int main()
{
std::ofstream file("file.txt");
file << "12345 \n";
}
转储该文件的输出并将其与原始文件进行比较。
问题是不同的平台有不同的线路终止序列。我只想验证“0x0A”是否是您平台的线路终止序列。请注意,当以文本模式读取文件时,行终止序列将转换为“\n”,而当您以文本模式将“\n”输出到文件时,行终止序列将转换为行终止序列。
Edit 2
所以我有文件:file.txt
> od -ta -tx1 file.txt
0000000 1 2 3 4 5 sp nl
31 32 33 34 35 20 0a
0000007
所以该文件包含 1 行以0x0A
使用该程序:
#include <iostream>
#include <sstream>
#include <string>
#include <iterator>
#include <fstream>>
#include <iomanip>
#include <algorithm>
int main()
{
std::ifstream file("file.txt");
std::string line;
while(std::getline(file,line))
{
std::cout << "Line(" << line << ")\n";
}
}
I get:
> g++ t.cpp
> ./a.out
Line(12345 )
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)