C++ 无法使用fstream逐行读取文件;按整个文件读取ok
1.我试图逐行读取文件,但它不会。我以前一步读取整个文件,没有问题。作为实验,我将接收数据的向量更改为本地向量(未成功)。我怀疑我做错了什么,除了对我C++ 无法使用fstream逐行读取文件;按整个文件读取ok,c++,file-io,C++,File Io,1.我试图逐行读取文件,但它不会。我以前一步读取整个文件,没有问题。作为实验,我将接收数据的向量更改为本地向量(未成功)。我怀疑我做错了什么,除了对我 int full_file_read( std::vector<std::string> &data , const std::string& filename , bool is_binary ) { std::string line ;
int
full_file_read( std::vector<std::string> &data ,
const std::string& filename ,
bool is_binary )
{
std::string line ;
std::ios_base::openmode openmode = std::ios::ate | std::ios::in ;
if ( is_binary )
{
openmode |= std::ios::binary ;
}
std::fstream file( filename , openmode ) ;
if ( !file )
{
std::cerr << "Can't open input file! "
<< filename << std::endl ;
}
std::vector<std::string> text ;
// to verify that it likes the push back for data is not the problem
if ( file.is_open() )
{
while ( std::getline( file , line ) )
{
text.push_back( line ) ;
// data.push_back( line ) ;
}
}
else
{
std::cerr << "Opening of " << filename
<< " failed!" << std::endl ;
}
std::cout << "file contents: " << std::endl ;
for ( auto const& c : line )
{
std::cout << c << ' ' << std::endl ;
}
return 0 ;
}
tia
std::ios::ate
表示在文件末尾打开。通常,只有在写入文件时才使用此选项,而在读取文件时不希望使用此选项。通过将其包含在这里,您可以在第一次getline
时获得文件的结尾
我无法解释SEGFULT,它通常是由未定义的行为引起的。可能是在这个函数返回后的代码中。我做了更改,感谢您指出错误。现在来看一个奇怪的部分:它读取文件,回显行并返回到return语句,但没有。它跳回open语句。奇怪!!我做了那个改变,谢谢你指出错误。现在来看一个奇怪的部分:它读取文件,回显行并返回到return语句,但没有。它跳回open语句。奇怪!!(请原谅我重复的话,因为我刚刚习惯了)没关系!现在问题在于调用函数,所以让我们调用这个solved/closed函数
i have a comment here
and another over there
yet another in somewhere unknown
for reasons only (dr) who noses
NumParticles|SimWidth|SimHeight|ViewWidth|ViewHeight|Softener|Zoom|MouseX|MouseY|MassMin|MassMax|CenterMass|DiskMin|DiskMax
10000000,327680,327680,1366,768,10,1,0,0,1,2,100000,2000000,5