C++ 将数字文件读入向量

C++ 将数字文件读入向量,c++,vector,file-io,C++,Vector,File Io,网上也有类似的问题,但他们没有给出充分的回答。我试图使用ofstream对象将3个随机数写入名为“mydata.txt”的文件,并使用ifstream对象从“mydata.txt”中提取这3个随机数。这是我的密码: ofstream myOFile {"mydata.txt"}; //open a file using the ofstream default constructor for(int i = 0; i<3;i++) { myOFile << (rand(

网上也有类似的问题,但他们没有给出充分的回答。我试图使用ofstream对象将3个随机数写入名为“mydata.txt”的文件,并使用ifstream对象从“mydata.txt”中提取这3个随机数。这是我的密码:

ofstream myOFile {"mydata.txt"}; //open a file using the ofstream default constructor
for(int i = 0; i<3;i++) {
    myOFile << (rand() % 100) << "\n"; //write random numbers from 0 to 99 to myOFile
}

ifstream myIFile {"mydata.txt"}; //open the same file using the ifstream default constructor
int nums;
vector<int> numsV;
while(myIFile >> nums) { // myIFile >> nums is false when end of file is reached
    numsV.push_back(nums); //add the numbers to a vector of ints called numsV
}

cout << numsV.size() << endl; //Why does this output zero?

for(int i : numsV) {
    cout << i << endl; //Why is nothing ouputted here?
}
流myOFile{“mydata.txt”}的
//使用ofstream默认构造函数打开文件
当到达文件末尾时,for(int i=0;i>nums)为false
numsV.push_back(nums);//将数字添加到名为numsV的整数向量中
}

您是否可能需要在完成写入后关闭该文件。下次,在internet上搜索“c++读取文件编号向量”。这个问题在StackOverflow上已经讨论过很多次。或者将您的标题更改为“我读取文件有什么问题”@user253751谢谢!这很有效。我假设文件在for循环后会隐式关闭,但它仍然在作用域中。