首页 > 解决方案 > 将数字文件读入向量

问题描述

网上也有类似的问题,但都没有给出充分的答复。我正在尝试使用 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?
}

当我查看计算机上的物理文件 mydata.txt 时,我可以在文档上看到 3 个随机数,这意味着对文件的写入有效。为什么我不能读取文件?

标签: c++vectorfile-io

解决方案


推荐阅读