我一个月前开始学习C ++并偶然发现了一些奇怪的事情:
我尝试将文件中的数据读入矢量(或者简单地用std :: cout写出来)。但是,在文件包含一定数量的数据之前,没有任何反应。 如果我的文件只包含整数,那么在读取内容之前元素的数量是1861,其中1860个元素将被附加到向量中。 但是,此数字可能会有所不同,具体取决于您的系统。
我构建了一个最小的例子:
#include <iostream>
#include <fstream>
#include <vector>
int main()
{
std::ofstream out( "newFile" );
const int NumberElements = 1860;
for( int index = 0; index != NumberElements; ++index )
{
out << index << " ";
}
//This sucessfully fills the file up until here
std::vector<int> readInHere;
std::ifstream in( "newFile" );
int temp;
while ( in >> temp )
{
readInHere.push_back( temp );
}
std::cout << readInHere.size() << '\n'; //This prints out 0
return 0;
}
我不知道这里发生了什么,如果你能帮我理解,我真的很感激。 我已经尝试过google了,但我可能错过了正确的标语来找到有用的东西。
感谢您的帮助!
答案 0 :(得分:0)
您需要调用out.close();
以确保刷新缓冲区并且可以开始阅读。
答案 1 :(得分:0)
写入后你没有关闭文件,stream
没有必要立即在文件中写入数据,它具有性能缓存机制,强制保存你需要调用(out.flush()
或{ {1}})。
out.close()